FAQ Database Discussion Community

## Hackkerrank BitFlipping Challenge

java,bit-manipulation,unary-operator
Most are probably familiar with this problem but for those who are not: Given 32-bit unsigned integers flip their bits and print the resulting integers. I was hoping that someone can give me clueson how to solve this in Java. Now I would normally provide some code i have tried...

## Calculating floating points as binary

double,bit-manipulation,point,floating
The question is : x and y are two floating point numbers in 32-bit IEEE floating-point format (8-bit exponent with bias 127) whose binary representation is as follows: x: 1 10000001 00010100000000000000000 y: 0 10000010 00100001000000000000000 Compute their product z = x y and give the result in binary IEEE...

## what (r+1 + (r >> 8)) >> 8 does?

c,bit-manipulation
In some old C/C++ graphics related code, that I have to port to Java and JavaScript I found this: b = (b+1 + (b >> 8)) >> 8; // very fast Where b is short int for blue, and same code is seen for r and b (red & blue)....

## Bitwise operations with int

c++,c,int,byte,bit-manipulation
Excuse me for my english. I have a number of int values stored in it from 0 to 255. To find out what lies in 7 bit number, I translate the numbers into a binary system, then in the line and check the line: if (informationOctet_.substr(6, 1) == "0") {...

## How to get specific bit segments of an integer in C?

c,bit-manipulation,bit
You are given a getTemps() function returns an integer composed of: the daily high temperature in bits 20-29, the daily low temperature in bits 10-19, and the current temperature in bits 0-9, all as 2's complement 10-bit integers. Write a C program which extracts the high, low, and current temperature...

## SIMD signed with unsigned multiplication for 64-bit * 64-bit to 128-bit

c,x86,integer,bit-manipulation,sse
I have created a function which does 64-bit * 64-bit to 128-bit using SIMD. Currently I have implemented it using SSE2 (acutally SSE4.1). This means it does two 64b*64b to 128b products at the same time. The same idea could be extended to AVX2 or AVX512 giving four or eight...

## Fastest way to sum digits using bit operations when summing color values

java,bit-manipulation
My particular case of summing digits deals with colors represented as integer. Java function BufferedImage.getRGB returns image in 0x00RRGGBB format. I'm making a function that gives you grayscale (color independent) sum of colors on the image. Currently, my operation looks very naive: //Just a pseudocode int sum = 0; for(x->width)...

## Bitwise operations to produce power of two in Python

python,bit-manipulation,music
In just intonation theory, a type of music theory, intervals between notes are expressed with rational numbers. Doubling a frequency with a 2:1 ratio brings it up an octave and a 1:1 ratio is no change; a unison. So if I have an interval n that is larger than an...

## Shift operation in C

c,bit-manipulation,bit-shift
Is it possible to shift 0s as you can shift 1s in shifting operation in C? Something like this for (i=0; i<32; i++) { if (data & 0x01) { data |= (1<<i); } else { data &=~ (0<<i); } } I'm checking if some bits are set and depending on...

## In Python how do I parse the 11th and 12th bit of 3 bytes?

python,parsing,python-3.x,bit-manipulation,bin
If I have 3 bytes b'\x00\x0c\x00', which can be represented with the bits 00000000 00001100 00000000, how do I then parse the 11th and 12th bit 11 most efficiently? Here positions: ** 00000000 11111110 22222111 tens 87654321 65432109 43210987 ones |||||||| |||||||| |||||||| 00000000 00001100 00000000 ** I have the...

## Converting bytes to a long: Why do some implementations bitwise-AND each byte with 0xff?

java,type-conversion,bit-manipulation,byte,long-integer

## Determine if an Enum with FlagsAttribute has unique bit values

c#,.net,enums,bit-manipulation
Consider the following enumeration: [Flags] public enum EnumWithUniqueBitFlags { None = 0, One = 1, Two = 2, Four = 4, Eight = 8, } [Flags] public enum EnumWithoutUniqueFlags { None = 0, One = 1, Two = 2, Four = 4, Five = 5, } The first one has...

## JAVA (Android) bitwise operator on strings

java,android,bit-manipulation,bitwise-operators
I am getting mad, i need to create a token using this operator PHP a = "hello"; b = "world"; token = a | b; well i need create the same in java [android] but i ever get error. I alredy try to: - cast the 2 strings to long...

## Best way to extract ODD digits from a binary number

algorithm,bit-manipulation
Given a 64 bit number, I need to extract every other bit from it, and convert it into a number: decimal: 357 binary: 0000 0001 0110 0101 odd bits: 0 0 0 1 1 0 1 1 decimal: 27 Any idea of a good algorithmic way to do it? And...

## Javascript bit shift to 32 bits

javascript,bit-manipulation
I have an array of ints var ints = [R,B,G,A] and I want to use shifting to get a 32-bit representation var thirtyTwo = AGBR so for example, [255.0, 0.0, 0.0, 255.0] => 0xFF0000FF => 4278190335 I'm attempting to do this with a loop and bitshift: function cArrayToABGR(va) { var...

## Bitwise operation bit check

c,bit-manipulation,bitwise-operators,bit-shift
Is this correct way to check if bits are set in some variable and store them in another variable? Just ignore variable names, image[] and mask variables are 1 byte and first_hline_first_row and second_hline_first_row are 2 byte. for(i=0; i<16; i++){ if(image[i] & mask1) first_hline_first_row |= (1<<i); else first_hline_first_row &=~ (0<<i);...

## Odd Pair of XOR in a large input Arrays

java,arrays,bit-manipulation,xor
You are given an array A1,A2...AN. You have to tell how many pairs (i, j) exist such that 1 ≤ i < j ≤ N and Ai XOR Aj is odd. Input and Output First line T, the number of testcases. Each testcase: first line N, followed by N...

## Bitwise and of subsets of an array

arrays,set,bit-manipulation,bitwise-operators
Can anyone give a hint how to approach this problem? Given an array A. Is there any subset of array A in which if we do AND of all elements of that subset then output should be in power of two. I've thought of generating a power-set and solving but...

## Create double by appending binary representations of two ints

c,binary,double,bit-manipulation,arc4random
I'm trying to create a double by appending the binary representations of two ints. This is what I have now: int i = arc4random(); *(&i+1) = arc4random(); double d = *(double*)&i; I hoped the double pointer would also use the value in the &i+1 address, and this is indeed the...

## Bit twiddling to get sign bit of 32 bit int

bit-manipulation
I would like to convert (n < 0 ? 1 : 0) into bit twiddling (assuming 2s complement arch). for performance reasons....

## Bit operations resulting in an unsigned large number instead of a negative number

python,bit-manipulation
>>> result = 0 >>> x = -2 >>> >>> for i in range(32): ... c = 1 << i ... if c & x: result |= c ... >>> print(result) 4294967294 As you can see, the expected result should be -2, however the program prints 4294967294, which is the...

## php best way to negate string of bits

php,bit-manipulation
I have an array of string bits of variable length and I need to negate them. eg. input array("1", "00101", "101", "0000") output array("0", "11010", "010", "1111") Is there a simple way how to do that?...

## Check if byte has more than one bit set [duplicate]

c#,bit-manipulation,byte
This question already has an answer here: C#. Logical riddle with bit operations. Only one bit is set? 3 answers I'm receiving a 3-byte message back from a serial device when I send it a query in my C# application. The entire message should have at most one bit...

## Find set bits and shift them to left most position using 32 bits

c,hex,bit-manipulation
I am trying to figure out how to find all set bits in a hex number and then shift those bits to the left most positions using a 32 bit notation. My program reads in args from the command prompt and then calls the appropriate function and passes either the...

## Bit Shifting leaving out zeros

bit-manipulation,bit-shift
I have this: int line = 0; line |= (1 << 0); line |= (1 << 1); line |= 0000000000; I was expecting an output of 000000011. But the output is 11. Why is my result truncated? I am using Java. So System.out.print();...

## Modulus in a for loop for creating a rectangle

algorithm,for-loop,bit-manipulation,modulus
This is an incredibly specific question, as i simply need to know if this pattern has a name and if there is a more effective way of doing it. (disregard the obvious declaration in the for loop) for (int i = 0; i < 8; i++) { int mod =...

## How that helps to convert

bit-manipulation
There is not my front-end code that is converting X from int to short and save it in a binary stream write(x & 0xFF) write((x & 0xFFFF) >> 8 ) (I am C++ back-end dev and not sure what the language this is.. looks like JS but there is no...

## why shift int a=1 to left 31 bits then to right 31 bits, it becomes -1 [duplicate]

c++,bit-manipulation
This question already has an answer here: What are bitwise shift (bit-shift) operators and how do they work? 5 answers given int a = 1; (00000000000000000000000000000001), what I did is just a=(a<<31)>>31; I assume a should still be 1 after this statement (nothing changed I think). However, it turns...

## Bitwise AND operation with a signed byte

java,bit-manipulation
Here is the code: int i = 200; byte b = (byte) 200; System.out.println(b); System.out.println((short) (b)); System.out.println((b & 0xff)); System.out.println((short) (b & 0xff)); Here is the output: -56 -56 200 200 Bitwise AND with 0xff shouldn't have changed anything in b, but apparently it does have an effect, why?...

## Rational comparison of bits

c++11,int,bit-manipulation,bit
I have a number of type int. It lies within [0,255]. That is, includes 8 bits. I need to check often say: 2(int) = 00000010(Binary) 1. The bit 6 and bit 7 must be equal to 0 and 1 respectively. And I check it like this: if ((!(informationOctet_ & (1...

## Weird bit manipulation in Python

python-2.7,bit-manipulation
Following are results of running the bin builtin function on the Python 2.7.2 interpreter: bin(5) => '0b101' bin(-5) => '-0b101' bin(5&-5) => '0b1' With infinite bits and 2's complement: +5 = 0000...0101 -5 = 1111...1101 Then why is 5&-5 = 0000...1? Shouldn't it be 0000...101? What's the explanation for this?...

## Numpy: check whether a bit is set to 1 or 0 in an array?

python,numpy,bit-manipulation,bit,bitstring
Suppose the following: bitstring = numpy.random.random_integers(0,2**32,size=8).astype(numpy.uint32) How can I find out which of the 256 bits are set to 1? I've got this... but this is crazy, isn't it? maximum = (2**32)-1 for checkbit in range (256): yes = bool(numpy.bitwise_and((2**checkbit)%maximum, bitstring[ ( (checkbit // maximum) + checkbit % maximum )...

## Understanding ~ Operator

operators,bit-manipulation
I am learning Bitwise Operators and for that I pulled out an article on tutsplus. Well, it is written quite nicely. I could understand the & and | operator but the ~ is messing things up. For example, as stated there in the article: In fact, just as ! flips...

## Getting bit-pattern of bool in Swift

swift,int,boolean,type-conversion,bit-manipulation
In ObjC, a bool's bit pattern could be retrieved by casting it to a UInt8. e.g. true => 0x01 false => 0x00 This bit pattern could then be used in further bit manipulation operations. Now I want to do the same in Swift. What I got working so far is...

## Setting a bit in hexadecimal number

c,bit-manipulation,bit
given a number (int a = 0XABCDE98) i am trying to set the D bit to 6. ie after the Bit manipulation the number should be (0XABC6E98). I have written the small C program to do the bit manipulation, but somehow i am not able to see the correct bit...

javascript,node.js,bit-manipulation,tostring,parseint
This question is similar to this other question; however, I'd like to understand why this is working as it is. The following code: console.log((parseInt('0xdeadbeef', 16) & parseInt('0x000000ff', 16)).toString(16)); console.log((parseInt('0xdeadbeef', 16) & parseInt('0x0000ff00', 16)).toString(16)); console.log((parseInt('0xdeadbeef', 16) & parseInt('0x00ff0000', 16)).toString(16)); console.log((parseInt('0xdeadbeef', 16) & parseInt('0xff000000', 16)).toString(16)); console.log((parseInt('0xdeadbeef', 16) &...

## PHP bitwise AND (&) returns negative number

php,bit-manipulation,32-bit
The code: echo (5243960811416 & 4040906070209050); Try on http://phptester.net/ and the result (right) will be 20407554584 but on my web hosting it gives -1067281896. There's any workaround to have 20407554584? It's a 32bit limit? Thanks UPDATE /w SOLUTION...

## Bit shift operations on a byte array in Java

java,bit-manipulation
How do I shift a byte array n positions to the right? For instance shifting a 16 byte array right 29 positions? I read somewhere it can be done using a long? Would using a long work like this: Long k1 = byte array from 0 to 7 Long k2...

## Most efficient way of looking up the results of a Bitwise operation

c#,bit-manipulation,bitwise-and
I've got some code in another language which uses an enum and a list of values from the enum and then uses bitwise to get an integer for the list of values from the enum. HELLO = 1 WORLD = 2 AND = 4 SO = 8 ON = 16...

## How to set and clear different bits in a single instruction (C)

c,bit-manipulation,bitwise-operators,firmware
data |= (1 << 3) sets bit (3) without disrupting other bits. data &= ~(1 << 4) resets bit (4) without disrupting other bits. How can I accomplish both tasks in a single instruction? (As this is really only for readability, I plan on #defineing this in a cute way...

## reverse a number's bits

c++,bit-manipulation
Here is a C++ class for revering bits from LeetCode discuss. https://leetcode.com/discuss/29324/c-solution-9ms-without-loop-without-calculation For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000). Is there anyone can explain it? Thank you so very much!! class Solution { public: uint32_t reverseBits(uint32_t n) { struct bs...

## Implementing “logical not” using less than 5 bitwise operators

c,bit-manipulation,micro-optimization
As part of my CS classes I've recently completed the pretty popular "Data Lab" assignments. In these assignments you are supposed to implement simple binary operations in C with as few operations as possible. For those who are not familiar with the "Data Lab" a quick overview about the rules:...

## How to swap endianness of Int16 without BitConverter

c#,.net,binary,bit-manipulation,endianness
I need to read binary files containing millions of Int16 stored as big endian. My first method was to use BitConverter and Array.Reverse() but that appears too slow for my purpose. Is there a way to do it with bitwise arithmetic instead ?...

## What is my code for inverting all the bits in a 32 bit integer producing the incorrect output?

java,algorithm,integer,bit-manipulation
This is from a hacker rank practice problem(not a competition) https://www.hackerrank.com/challenges/flipping-bits. Just doing this for practice. The problem just asks you to take a set number for 32 bit integers and for each one, invert all the bits inside that integer and print out the result Here's my code so...

## Need some help - left shift bitwise operator

c++,bit-manipulation,operators
I am trying to clearly understand the behaviour of the shift operators (especially for the boundary cases), so I devised a little test written in C++. int a = odd_value; //321 in my case but it should not matter (the last bit to be 1) print(0, a); a = a...

## Can someone explain this bitwise C code?

c,bit-manipulation
I don't know what's going on with this: #define _PACK32(str, x) \ { \ *(x) = ((int) *((str) + 3) ) \ | ((int) *((str) + 2) << 8) \ | ((int) *((str) + 1) << 16) \ | ((int) *((str) + 0) << 24); \ } the str it's...

## Rotate right using bit operation in c

c,bit-manipulation,bit
I am trying to come up with a function int rotateRight(int x, int n) that Rotate x to the right by n. For example,rotateRight(0x87654321,4) = 0x76543218. This is what I have so far int rotateRight(int x, int n) { int mask = (((1 << n)-1)<<(32-n)); int reserve = (int)((unsigned) (x&mask)...

## BitCount Method

java,bit-manipulation
Can anyone Explain this bitcount method. public static int bitCount(int i) { // Hacker's Delight, Figure 5-2 i -= (i >> 1) & 0x55555555; i = (i & 0x33333333) + ((i >> 2) & 0x33333333); i = ((i >> 4) + i) & 0x0F0F0F0F; i += i >> 8; i...

## Ambiguous pseudocode phrase

c++,bit-manipulation,pseudocode
I was looking though some pseudocode for some code and I came across the phrase lowest 32 bits of After a very long time of searching through website I came across the answer: What we want to do is AND operation on 64 bit number and 0xffffffff to get lowest...

## C - operations on bits representing a structure

c,hash,bit-manipulation
I'm trying to write hashset in C, and I've found one hash function, that hashes according to bits in data. I have the following structure: struct triple { int a; int b; int c; }; The question is - how to get bit representation from object of type struct triple?...

## C++ return bool with && in return statement - need clarification

c++,return,bit-manipulation,ampersand
I'm not entirely sure what happens in this process and what the outcome would be. I've never come across using && in a return or especially a single one in the same return statement. bool myfunction(unsigned int x) { return x && !(x & (x­ - 1)); } I'd love...

## Bitwise XOR in VB.NET

vb.net,bit-manipulation,xor
I'm trying to get an application to XOR two hexadecimal values and output the result as a decimal value. I have searched the Internet for an answer, but every result simply gives a true or false result. The figures I am using as an example are Value 1 = 0F8F...

## A + B without arithmetic operators, Python vs C++

python,c++,algorithm,bit-manipulation
I was trying to solve an old question: Write a function that add two [integer] numbers A and B. You should not use + or any arithmetic operators. The best solution is like this, quote from here: For a + b in any base, we can treat the plus as...

## How can I test if all bits are set or all bits are not?

c++,c,bit-manipulation
Using bitwise operator how can I test if the n least significant bits of an integer are either all sets or all not sets. For example if n = 3 I only care about the 3 least significant bits the test should return true for 0 and 7 and false...

## How to generate a new int with a specific amount of bits in it

java,bit-manipulation,bit
The Problem Hi there, i recently moved to using a binary representation for a domain in my program, this enhanced the speed of calculations with that domain, but i now need a method of generating ints based on an input number of bits needed. My application is in Java so...

## Bit shifting in IBM assembler

assembly,bit-manipulation,mainframe
In IBM OS/390 assembly, I am trying to do the following: I have a set of bits that all end in 2 zeroes: 00xxxxxx 00yyyyyy 00zzzzzz I want to compress them into the following format: xxxxxxyy yyyyzzzz zz... I figure that the order will something like ICM R7,B'1111',FIRSTBUF LOAD 4...

## Java XOR operation

java,algorithm,bit-manipulation,xor,bitwise-xor
I came across this problem wherein all of the program was given barring only a piece of logic. What could be filled in the following problem's missing lines? Problem Statement Jack and Daniel are friends. They want to encrypt their conversation so that they can save themselves from interception by...

## using bitwise and operator c++

c++,bit-manipulation,bit,bitwise-operators
I have the following code int n = 50; while(n) { //1 if(n & 1) cout << "1" << endl; //2 //right shift the number so n will become 0 eventually and the loop will terminate n >>= 1; //3 } When we use bitwise and 1 (& 1) with...

## Why does -9 & 0xaaaa get an unsigned result?

java,bit-manipulation
The method convertToBinary is used to show the 8bit binary number, public static String convertToBinary(int a){ String binary=""; for(int i=0;i<8;++i){ Integer bit=new Integer(a&1); binary=bit.toString()+binary; a>>=1; } return binary; } public static void main(String[] args) { int a=-9; System.out.println(convertBinary(a)); //11110111 System.out.println(convertBinary(0xaaaa)); //10101010 System.out.println(convertBinary(a&0xaaaa)); //10100010 System.out.println(convertBinary((a&0xaaaa)>>1));//01010001 } The last...

## Distance span between two binary strings

bit-manipulation
Is there any way of finding efficiently (bitwise operations) the distance (not Hamming Distance!) of two 8-bit binary strings? Each byte is guaranteed to have only one bit set. Like: a=0 0 0 0 0 0 0 1 b=0 0 0 1 0 0 0 0 0 0 0 1...

## bit shifting in c returning wrong result

c,bit-manipulation,machine-code
I'm writing code to translate machine code. readFiveBytes is inside of a loop and supposed to take one byte at a time and place each byte into its correct place and return an address in the end. void readFiveBytes(int c) { if (counter != 0) { currentIns = currentIns |...

java,bit-manipulation,nio
I've been following this tutorial, it's quite helpful and most things are making sense. If you look on page 34 you'll see this snippet of code: } else if ((key.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) { // Read the data SocketChannel sc = (SocketChannel)key.channel(); // ... } What exactly is going...

## packing an array of 3 values in buffer

c++,c,memory,bit-manipulation,information-theory
I have the following problem I am unable to solve gracefully. I have a data type that can take 3 possible values (0,1,2). I have an array of 20 element of this data type. As I want to encode the information on the least amount of memory, I did the...

## How to do a bit representation in a C-standard way?

c,bit-manipulation,standards,bit
As per the C standard the value representation of a integer type is implementation defined. So 5 might not be represented as 00000000000000000000000000000101 or -1 as 11111111111111111111111111111111 as we usually assume in a 32-bit 2's complement. So even though the operators ~, << and >> are well defined, the bit...

## Bitmask and -offset by offset and length

c#,.net,bit-manipulation,bit-shift
I want to create a bitmask and the bitmask offset by offset and length. For example: offset = 8 and length = 4 the bitmask should be: 0xF00 = 3840 in decimal(1111.0000.0000) and the bitoffset should be: 0x100 = 256 in decimal I've tried the following, but that's wrong: ulong...

## Check if bit has toggled in C

c,bit-manipulation,toggle
I am working on bitwise manipulation (in C) and I wanted to know how to check if a bit has toggled between a previous value and the new value. Example : oldValue = 0x0FF //0000 1111 1111 in binary newValue = 0x100 //0001 0000 0000 in binary In this example...

## Fast bit shift of a byte array - CMAC subkeys

performance,cryptography,bit-manipulation,bit-shift,javacard
I need to implement as fast as possible left bit shift of a 16-byte array in JavaCard. I tried this code: private static final void rotateLeft(final byte[] output, final byte[] input) { short carry = 0; short i = (short) 16; do { --i; carry = (short)((input[i] << 1) |...

## Getting four bits from the right only in a byte using bit shift operations

c,syntax,bit-manipulation,bitwise-operators
I wanted to try to get only the four bits from the right in a byte by using only bit shift operations but it sometimes worked and sometimes not, but I don't understand why. Here's an example: unsigned char b = foo; //say foo is 1000 1010 unsigned char temp=0u;...

## what does '|' mean in JavaScript? [duplicate]

javascript,syntax,bit-manipulation
This question already has an answer here: What does the “|” (single pipe) do in JavaScript? 3 answers I've seen a single | being used in code somewhere but I have no idea what it means. I know that || is 'or'. I typed it in the console and...

## How to do bitwise operation decently?

matlab,bit-manipulation,octave
I'm doing analysis on binary data. Suppose I have two uint8 data values: a = uint8(0xAB); b = uint8(0xCD); I want to take the lower two bits from a, and whole content from b, to make a 10 bit value. In C-style, it should be like: (a[2:1] << 8) |...

## Efficient comparison of small integer vectors

c,integer,compare,bit-manipulation,string-comparison
I have small vectors. Each of them is made of 10 integers which are between 0 and 15. This means that every element in a vector can be written using 4 bits. Hence I can concatenate my vector elements and store the whole vector in a single long type (in...

## Efficiency of bitwise operation in Javascript

javascript,performance,bit-manipulation
According to w3schools Unlike many other programming languages, JavaScript does not define different types of numbers, like integers, short, long, floating-point etc. JavaScript numbers are always stored as double precision floating point numbers, following the international IEEE 754 standard. So my question comes: if we want to perform a bitwise...

## Byte Array to Byte conversion error

c#,bit-manipulation,byte,bytearray,implicit-conversion
I am trying to flip the bits of an unsigned 32-bit integer and output the resultant integer. The following is my code. int numberOfTries = Convert.ToInt32(Console.ReadLine()); for (int i = 0; i < numberOfTries; i++) { uint input = Convert.ToUInt32(Console.ReadLine()); byte[] bInput = BitConverter.GetBytes(input); if (BitConverter.IsLittleEndian) Array.Reverse(bInput); byte[] result =...

## Perform integer division using multiplication

assembly,optimization,bit-manipulation,division,multiplication
Looking at x86 assembly produced by a compiler, I noticed that (unsigned) integer divisions are sometimes implemented as integer multiplications. These optimizations seem to follow the form value / n => (value * ((0xFFFFFFFF / n) + 1)) / 0x100000000 For example, performing a division by 9: 12345678 / 9...

## Converting bits of a byte to single bits and back

c,bit-manipulation,bitwise-operators,stm32
I have the struct below typedef struct fpButtons { /** BYTE 0 **/ uint8_t button_1:1; uint8_t button_2:1; uint8_t button_3:1; uint8_t button_4:1; uint8_t button_5:1; uint8_t button_6:1; uint8_t button_7:1; uint8_t button_8:1; /** And BYTE 2 which I didn't paste to save SO's space lol **/ // button_9:1 to button_16:1 } FP_BUTTONS; And...

## why does a variation in the if statement of this bitwise operation cause an error?

c++,bit-manipulation
I am writing a function to print bits but i ran into a problem. The two for loops seem identical to me but for some reason the one that is commented out does not print the right bits. int main() { unsigned int bits = 0x570FA1; unsigned int mask =...

## Toggle a given range of bit of an unsigned int in C

c,bit-manipulation
I am trying to replace the following piece of code // code version 1 unsigned int time_stx = 11; // given range start unsigned int time_enx = 19; // given range end unsigned int time = 0; // desired output while(time_stx < time_enx) time |= (1 << time_stx++); with the...

## Counting the number of leading zeros in a 128-bit integer

c++,gcc,bit-manipulation,sse
How can I count the number of leading zeros in a 128-bit integer (uint128_t) efficiently? I know GCC's built-in functions: __builtin_clz, __builtin_clzl, __builtin_clzll __builtin_ffs, __builtin_ffsl, __builtin_ffsll However, these functions only work with 32- and 64-bit integers. I also found some SSE instructions: __lzcnt16, __lzcnt, __lzcnt64 As you may guess, these...

## Java Bitwise Or Between Byte and Int

java,binary,bit-manipulation,twos-complement,sign-extension
I am trying to perform a bitwise or on a byte value I have in Java. For example, I am running: byte b = (byte)0b11111111; int result = 0 | b; My expected result for this would be 0b00000000 00000000 00000000 11111111, or 255. However, I am receiving -1, or...

## Back and forth calculation of integer Identifier using bit shifting and OR operations

c#,.net,bit-manipulation,bit
Good morning, don't know if this question is hitting the right StackExchange network. If not please forgive me. I got an decimal/integer identifier value which i need to split into three separate values. Lets assume we have program ABC. Program ABC is generating the decimal/integer identifier value using this formula:...

## Update bits error on one testcase

java,algorithm,bit-manipulation
Given two 32-bit numbers, N and M, and two bit positions, i and j. Write a method to set all bits between i and j in N equal to M (e g , M becomes a substring of N located at i and starting at j) Example Given N=(10000000000)2, M=(10101)2,...

## How to get most significant n bits from int in java

java,caching,bit-manipulation
I have an int, and I would like to get the 19 most significant bits in java. I tried all sorts of methods, none of them work. Can someone please help me?

## fast way to get integers 0, 1, and 2 when given a random one from the set

c++,c,bit-manipulation,bitwise-operators
So basically int num = rand(2); //random number from 0-2 int otherNum, otherOtherNum; otherNum = implement this otherOtherNum = implement this For example, if num is 2, otherNum and otherOtherNum must be set to 0 and 1 (or 1 and 0). How would you implement this? Assume you can't use...

## Swapping two bits in an integer as quickly as possible

bit-manipulation
I've been looking at some of these books with fun interview problems. One has a question where one is supposed to write code to flip two bits in a 64-bit integer given the indices of the two bits. After playing around with this for a while I came up with...

## Field packing byte returns unexpected results

objective-c,c,bit-manipulation,bitwise-operators
I've been experimenting with changing values for some of the bits for field packing a byte, based on my last question: Field packing to form a single byte However, I'm getting unexpected results based on the values. The top code sample gives me an expected output of 0x91, however if...

## What does the single & in the following statement mean?

c,bit-manipulation,bitwise-operators,bitwise-and
strcat(b, ((x & z) == z) ? "1" : "0"); I understand strcat() function and the conditional (ternary) operator. But I don't know what (x & z) == z means....

## How to get certain bits of a char array to another char array in C?

c,arrays,bit-manipulation
I have a char (input) array with size 60. I want to write a function that returns certain bits of the input array. char input_ar; char output_ar; void func(int bits_starting_number, int total_number_bits){ } int main() { input_ar=0b11110001; input_ar=0b00110011; func(3,11); //want output_ar=0b11000100; //least significant 6 bits of input_ar and most significant...

## Bit shifting and bit mask - sample code

java,bit-manipulation
I've come across some code which has the bit masks 0xff and 0xff00 or in 16 bit binary form 00000000 11111111 and 11111111 00000000. /** * Function to check if the given string is in GZIP Format. * * @param inString String to check. * @return True if GZIP Compressed...

## Bitwise (Bitshift) operations on 64-bit integers in C++

c++,bit-manipulation,bit-shift,bitwise-or,bitboard
I'm trying to deal with bitboards, which requires me to set a particular bit in a 64-bit unsigned integer. To set bit i, I perform a bitwise OR with the bitboard in question, with a left shifted number. #include <stdint.h> uint64_t kings = 0ULL; // Also tried unsigned long long...

## Unpack redis set bit string in Go

go,redis,bit-manipulation,bit
Using redis#Setbit to set bit in a key like: redis.Do("SETBIT", "mykey", 1, 1). When I read it using redis#Get like redis.Do("GET", "mykey"), I get a bit string. How do I unpack the string so I can get a slice of bools in Go? In Ruby, you use String#unpack like "@".unpack...

## Equal elements in SubArray

python,c++,algorithm,data-structures,bit-manipulation
I have an array containing N elements and I need to find the distance between the index of equal elements in a subarray; which we will get in form of query (L R) where L is starting index of subarray and R in ending index. Total No. of array elements...

## Why shift bits by 8 in Socket Programming - C?

c,sockets,ip,bit-manipulation
I am studying the FreeBSH Developers Handbook and there I am seeing this code for Socket programming: struct sockaddr_in sa; sa.sin_addr.s_addr = htonl((((((192 << 8) | 43) << 8) | 244) << 8) | 18); Why is the bitwise shift and or is used here? I know what bitwise shift...

## trouble using a mask to manipulate a bit

I'm working on a function that returns 1 when x can be represented as an n-bit, 2’s complement number and 0 if it can't. Right now my code works for some examples like (5,3),(-4,3). But I cant get it to work for instances where n is bigger than x like...

## High/low byte conversion for integer in ruby

ruby,integer,bit-manipulation,byte
We are having some small problems when converting data from hex to integer in ruby... We get a hardware signal, which is integer data -> converted to high and low byte, bitwise reversed -> string. Here is a example: Something between 0 and 75 => will be converted to "0x3938"......

## Consider 8th Bit in Python Byte to make Postive Integer

python,bit-manipulation,negative-number
I'm working on a Python Application that reads from a binary file, pulls a byte that then references a list. This is essentially what I'm doing. list = [x for x in range(0, 340)] index = struct.unpack('<b', file.read(1)) print(list[index]) The problem is that the file I'm reading from, the 8th...

## Counting non-zero bits in a list of 32-bit integers

python,python-3.x,bit-manipulation
Edit: Problem solved, advert your eyes from the below code though, haha, I had some things conceptually wrong from the beginning. I've been trying for longer than I care to admit to count the non-zero bits in a wide variety of 32-bit integers, but always seem a bit off. So...

## How do bit operations work?

c#,bit-manipulation
I have the following question: What will the output be when the following program runs: using System; class Example{ public static void Main(){ int t; byte val; val=123; for(t=128;t>0;t=t/2){ if((val &t)!=0) console.Write("1 "); if((val &t)==0) console.Write("0 "); } } } A.0 0 1 1 1 0 1 1 B.1 1...

## What is this code doing?

c,bit-manipulation,chess
const int BitTable = { 63, 30, 3, 32, 25, 41, 22, 33, 15, 50, 42, 13, 11, 53, 19, 34, 61, 29, 2, 51, 21, 43, 45, 10, 18, 47, 1, 54, 9, 57, 0, 35, 62, 31, 40, 4, 49, 5, 52, 26, 60, 6, 23, 44, 46,...

## Bitwise operations in java

java,bit-manipulation,shift,operations
what does this piece of code mean ...Can anyone explain how does this work.. sum += (i & (1<<j)) != 0 ? n[j] : 0; full code: int max = (1 << N)-1; //System.err.println(max); String res = "No"; for (int i = 0; i <= max; i++) { long sum...

## Checking byte with bitwise operators

c,bit-manipulation,byte,bit
I could use this: unsigned long alpha = 140 | 130 << 8 | 255 << 16; to set 140 to the first byte of alpha, 130 to the second and 255 as 3rd. How do I do the opposite (i.e checking a specific byte of alpha) ? alpha &...