bit-manipulation

Bit shifting in internet checksums.

This is almost certainly a very silly question, but for some reason I'm having trouble with internet checksum calculations. All of the algorithms basically look something like this: WORD chksm(WORD *startpos, WORD checklen){ ulong sum = 0; WORD answer = 0; while (checklen > 1) { sum += *startpos++; checklen -= 2; } if (checklen == ...

Two's Complement in Python

Is there a built in function in python which will convert a binary string, for example '111111111111', to the two's complement integer -1? ...

Branchless code that maps zero, negative, and positive to 0, 1, 2

Write a branchless function that returns 0, 1, or 2 if the difference between two signed integers is zero, negative, or positive. Here's a version with branching: int Compare(int x, int y) { int diff = x - y; if (diff == 0) return 0; else if (diff < 0) return 1; else return 2; } Here's a versio...

How many 1s in an n-bit integer?

An interesting problem I ran into today: what is the fastest way to count the number of 1s in an n-bit integer? Is it possible to beat O(n)? For example: 42 = 0b101010 => 3 ones 512 = 0b1000000000 => 1 one Clearly, the naive algorithm is to simply count. But, are there any tricks to speed it up? (This is merely an academic question;...

Find "edges" in 32 bits word bitpattern

Im trying to find the most efficient algorithm to count "edges" in a bit-pattern. An edge meaning a change from 0 to 1 or 1 to 0. I am sampling each bit every 250 us and shifting it into a 32 bit unsigned variable. This is my algorithm so far void CountEdges(void) { uint_least32_t feedback_samples_copy = feedback_samples; sign...

What is a better method for packing 4 bytes into 3 than this?

I have an array of values all well within the range 0 - 63, and decided I could pack every 4 bytes into 3 because the values only require 6 bits and I could use the extra 2bits to store the first 2 bits of the next value and so on. Having never done this before I used the switch statement and a nextbit variable (a state machine like dev...

Rotating a bitmap 90 degrees

I have a one 64-bit integer, which I need to rotate 90 degrees in 8 x 8 area (preferably with straight bit-manipulation). I cannot figure out any handy algorithm for that. For instance, this: // 0xD000000000000000 = 1101000000000000000000000000000000000000000000000000000000000000 1 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ...

Find min/max of a float/double that has the same internal representation

Refreshing on floating points (also PDF), IEEE-754 and taking part in this discussion on floating point rounding when converting to strings, brought me to tinker: how can I get the maximum and minimum value for a given floating point number whose binary representations are equal. Disclaimer: for this discussion, I like to stick to 32 bi...

How to reverse bits of a byte ?

Best in PHP, for example, 11011111 ==> 11111011 ...

How to think of bit operations for simple operations?

for example: unsigned int a; // value to merge in non-masked bits unsigned int b; // value to merge in masked bits unsigned int mask; // 1 where bits from b should be selected; 0 where from a. unsigned int r; // result of (a & ~mask) | (b & mask) goes here r = a ^ ((a ^ b) & mask); merges bits from two values according to th...

Do bitwise operations distribute over addition?

I'm looking at an algorithm I'm trying to optimize, and it's basically a lot of bit twiddling, followed by some additions in a tight feedback. If I could use carry-save addition for the adders, it would really help me speed things up, but I'm not sure if I can distribute the operations over the addition. Specifically if I represent: ...

Best Book on Bit Magic

Hi, I'm continiously impressed with the bitmagic used in chess engines, 3dgames and other highly optimized codebases. I've tried to read about IEEE and the article at topcoder, but I would like a more elaborate material, like a book. Do anybody know such a book, that describes the layout of IEEE, the bit tricks and the math behind them?...

Bit Hack - Round off to multiple of 8

can anyone please explain how this works (asz + 7) & ~7; It rounds off asz to the next higher multiple of 8. It is easy to see that ~7 produces 11111000 (8bit representation) and hence switches off the last 3 bits ,thus any number which is produced is a multiple of 8. My question is how does adding asz to 7 before masking [edit] prod...

How do I simulate a bitwise rotation of a 64-bit (unsigned) integer in JavaScript?

I need to perform a circular left shift of a 64-bit integer in JavaScript. However: JavaScript numbers are doubles JavaScript converts them to 32-bit signed ints when you start with the << and the >> and the >>> and the ~ and all of the bit-twiddling business. And then it's back to doubles when you're done. I think. I don't want the...

Bit Shifting, Masking or a Bit Field Struct?

Hi, I'm new to working with bits. I'm trying to work with an existing protocol, which can send three different types of messages. Type 1 is a 16-bit structure: struct digital { unsigned int type:2; unsigned int highlow:1; unsigned int sig1:5; unsigned int :1; unsigned int sig2:7; }; The first two bits (type, in my struct abov...

Finding Highest Order 1 in a Java Primitive

I need to find the highest order 1 in some longs, ints, and shorts in Java. For example, if I had a char that looked like 00110101, I need a method that will return 2 (index of highest order 1). Now, I know that you can do this using a for loop like: for(int i=0; i<8; i++) if((x & 1<<i) != 0) return i; return -1; but this is way ...

Extracting bits

In C, I have a 32bit word representing an address (and I have it stored in a unsigned long, hope thats ok). Now from what I gather, part of an address contains the page number and the other part contains the offset. I was wondering how I could extract just the bits that give me the page number. I have already worked out the first 22 mos...

Why is a 16-bit register used with BSR instruction in this code snippet?

In this hardcore article there's a function find_maskwidth() that basically detects the number of bits required to represent itemCount dictinct values: unsigned int find_maskwidth( unsigned int itemCount ) { unsigned int maskWidth, count = itemCount; __asm { mov eax, count mov ecx, 0 mov maskWidth, ecx ...

How can I read/write bits from/to a file in Java?

I need to read file stream as bits and then I should be able to write bits to file again. Are there any classes for this purpose? ...

Writing files in bit form to a file in C

i am implementing the huffman algorithm in C. i have got the basic functionality down upto the point where the binary codewords are obtained. so for example, abcd will be 100011000 or something similar. now the question is how do you write this code in binary form in the compressed file. i mean if i write it normally each 1 and 0 will be...