## How I can remove all odds bits in C?

I have int 136970250 (1000 0010 1010 0000 0000 0000 1010) -> I need to remove all odd bits(1, 3, 5, 7...) 1000 0010 1010 0000 0000 0000 1010 -> 10 0111 0000 0011 (9987) - because this bits do not have information. How to do it? ...
more »

## How to sort 400 mil. integers, where each one is repeated at most 2 times?

Given 400 million 32-bit integers, where each individual integer is repeated at most two time, how can you sort them? This in an interview questions. I proposed using a counting table with 2^32 entries -- each possible value has an entry, and each ...
more »

## Shifting with uint64_t not working as expected

For part of a larger task, I was asked to implement a function that flips an arbitrary bit in an integer. The catch is that the "integer" could be any of the default integer types in c, from int8_t to uint64_t, and I don't know which one it will be. ...
more »

## The index of the first bit

I can see in http://hackage.haskell.org/package/base-4.7.0.0/docs/Data-Bits.html#v:bit how to convert from an Int, n, to a Bit that has the nth bit set, using bit :: Int -> a However, how can I do the inverse of this? (Assuming the input Bit ju...
more »

## Reversing the bits of an integer in C

I am trying to reverse the bits of an integer in the C program. Even though I have looked at the same question by another user, I was unable to understand most of the code that was written. I have noticed that the code I have is similar to the answe...
more »

## Convert x >= y into 1 or 0 without branching or Boolean expressions

I need to implement the following function without branching or Boolean expressions: uint8_t func(uint32_t num, uint8_t shl) { if (num >= (1 << shl)) { return shl; } else { return 0; } } The first s...
more »

## Set bits combined with exponential modular arithmetics

I got this question yesterday in a challenge. I thought I had coded it correctly and my sample test case was passed. However not even a single test case passed at the backend. Here is my code. Please, someone, help me out. The challenge is over for...
more »

## How does & bit operator work here?

In Java Collection classes, I have noticed very often codes like below //ArrayDeque public E pollFirst() { int h = head; @SuppressWarnings("unchecked") E result = (E) elements[h]; // Element is null if deque empty if (resu...
more »

## What does the "^=" operator do in this find non-paired number algorithm?

Saw an interesting piece of code to find a lonely number in a list of duplicate numbers (where every number in the list occurs twice except for one). function findNonPaired(listOfNumbers) { let nonPairedNumber = 0 listOfNumbers.forEach((...
more »

## Fastest way to compute the opposite of the sign of a number in C

We all know sgn() function. It can be implemented in C like something along these lines: inline int sgn(int x) { if(x > 0) { return 1; } else if(x < 0) { return -1; } else { return 0; } } Or, a more ef...
more »

## Unusual behavior with shift-right bitwise operator

I'm writing a simple code in C (only using bit-wise operators) that takes a pointer to an unsigned integer x and flips the bit at the nth position n in the binary notation of the integer. The function is declared as follows: int flip_bit (unsigned ...
more »

## Find most significant bit in Swift

I need to find the value (or position) of the most significant bit (MSB) of an integer in Swift. Eg: Input number: 9 Input as binary: 1001 MS value as binary: 1000 -> (which is 8 in decimal) MS position as decimal: 3 (because 1<<3 == 1000) ...
more »

## Fast indexing and bit flipping of boolean data using Python

Using Python, I'm running a simulation where a community of species goes through a sequential set of time steps ('scenes') in each of which extinction occurs. From an initial set of N species, each extinction needs to select a number of survivors, wh...
more »

## How bit manipulation works?

There was a question asked: "Presented with the integer n, find the 0-based position of the second rightmost zero bit in its binary representation (it is guaranteed that such a bit exists), counting from right to left. Return the value o...
more »

## Efficient way to split up RGB values in C

I'm writing some software for a 32-bit cortex M0 microcontroller in C and I'm doing alot of manipulations with 32-bit RGB values. They are handled in a 32-bit integer format like 0x00BBRRGG. I want to be able to do math with them without worrying abo...
more »

## Bitwise Operations to change 2 LSB

Suppose I have an list of numbers: l = [30, 31, 32, 33] In binary this would the same as l = [00011110, 00011111, 00100000, 00100001] Using binary operations I want to set the least 2 significant bits to any random value, but retain the 6 most...
more »

## Optimized way to find new bits on

We need to find new bits turned ON in interlock status received from the device compared to the last status read. This is for firing error codes for bits that are newly set. I am using the following statement. bits_on =~last_status & new_status;...
more »

## Given two integers find a third integer which is different from the given two without using if statment

The question as mentioned above is as follows: Given two integers, x1 and x2, find another integer, x3, which is different from both x1 and x2 , without using the if keyword. My solution is based on bit wise operations on integers plus on the fact t...
more »

## Can a C compiler implement signed right shift "unreasonably"?

The title field isn't long enough to a capture a detailed question, so for the record, my actual question defines "unreasonable" in a specific way: Is it legal1 for a C implementation have an arithmetic right shift operator that returns differe...
more »

## Fastest Two Number Sign Comparison Including Zero

What is the fastest way to find if two numbers have the same sign considering that the sign can either be positive, negative or zero. Commonly, you can say two numbers have same signs with this: Math.signum(int1) == Math.signum(int2); You can opt...
more »

## Efficient parallel byte-wise computation of predicate "less than or equal" for signed integers

In various contexts, such as bioinformatics, computations on byte-size integers is sufficient. For best performance, many processor architectures offer SIMD instruction sets (e.g. MMX, SSE, AVX) which partition registers into byte-, halfword-, and wo...
more »

## C-language binary shift operator

I'm trying to learn some basic C for a project. On the Wikipedia article on binary shift operators: If the variable ch contains the bit pattern 11100101, then ch >> 1 will produce the result 01110010, and ch >> 2 will produce 00111001. Just fo...
more »

## Unable to convert a binary to decimal

My aim is to have a decimal which has same leading ones in binary as the user specifies, which is stored in the unsigned long variable mask; the remaining bits would be set to zero. int mask; scanf("%d",&mask); unsigned long subnetMask = 0; i...
more »

## I can't understand why I get this result when I bitwise OR a short and char

Could someone please explain why I get this result when I bitwise OR two numbers? I'm really confused. signed char signedChar = -64; // This is now -64, or 1100 0000 unsigned char unsignedChar = signedChar; // This is now 196, or 1100 0000 (T...
more »

## Type casting and Bit Manipulation Mystery

#include <stdio.h> #include <stdint.h> typedef unsigned char uint8_t; typedef short int16_t; typedef unsigned short uint16_t; typedef int int32_t; typedef unsigned int uint32_t; int main(){ ...
more »

## Negative numbers: How can I change the sign bit in a signed int to a 0?

I was thinking this world work, but it does not: int a = -500; a = a << 1; a = (unsigned int)a >> 1; //printf("%d",a) gives me "2147483148" My thought was that the left-shift would remove the leftmost sign bit, so right-shifting it as ...
more »

## Trying to find the number of x's that satisfies n + x = n ^ x fails with timeout

I'm trying to solve the following problem from the section Bit Manipulation at the Hacker Rank site using new features of Java 8 such as Streams. The problem description: Given an integer, n, find each x such that: 0 <= x <= n n ...
more »

## how to replace given nibbles with another set of nibbles in an integer

Suppose you have an integer a = 0x12345678 & a short b = 0xabcd What i wanna do is replace the given nibbles in integer a with nibbles from short b Eg: Replace 0,2,5,7th nibbles in a = 0x12345678 (where 8 = 0th nibble, 7=1st nibble, 6=2nd nibbl...
more »

## Unsigned Right Shift / Zero-fill Right Shift in PHP (Java/JavaScript equivalent)

Before flagging this as a duplicate, please read below, and check my code! So my problem is that, I have to implement Java/JavaScript '>>>' (Unsigned Right Shift / Zero-fill Right Shift), but I can't get it work exactly the same way. I've selected ...
more »

## Extracting bits from uint8_t type array

I have the data: ef324ad13255e219e8110044997cefaa43ff0954800000000000007 stored in an uint8_t type array called lfsr[36]. I want to extract specific bits from the array, e.g. bit no. 96, bit no. 184 etc. How can I perform this operation? ...
more »

## Optimising "i = b ? (i | mask) : (i & ~mask)"

I want to be able to set or clear (multiple) bits of a uintX_t t. i is a runtime variable (uintX_t). b is a runtime variable (uintX_t) which is constrained to be 0 or 1. mask is a compile-time constant. Is there a better way than: i = b ? (i | ma...
more »

## Checking the value of a bit in C

I am learning how to check the value of a bit. My textbook claims the following. 'Even if bit 1 in flags is set to 1, the other bit setting in flags can make the comparison untrue. Instead, you must first mask the other bits in flags so that you com...
more »

## How can an (int) be converted to (unsigned int) while preserving the original bit pattern?

Suppose that we define: short x = -1; unsigned short y = (unsigned short) x; According to the C99 standard: Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value th...
more »

## Efficiently dividing unsigned value by a power of two, rounding up

I want to implement unsigned integer division by an arbitrary power of two, rounding up, efficiently. So what I, mathematically, is ceiling(p/q)0. In C, the straw-man implementation, which doesn't take advantage of the restricted domain of q would so...
more »