bitfoo

Zig Zag Decoding

In the google protocol buffers encoding overview, they introduce something called "Zig Zag Encoding", this takes signed numbers, which have a small magnitude, and creates a series of unsigned numbers which have a small magnitude. For example Encoded => Plain 0 => 0 1 => -1 2 => 1 3 => -2 4 => 2 5 => -3 6 => 3 And so on. The encoding ...

Easiest way to find the correct kademlia bucket

In the Kademlia protocol node IDs are 160 bit numbers. Nodes are stored in buckets, bucket 0 stores all the nodes which have the same ID as this node except for the very last bit, bucket 1 stores all the nodes which have the same ID as this node except for the last 2 bits, and so on for all 160 buckets. What's the fastest way to find wh...

Setting last N bits in an array

I'm sure this is fairly simple, however I have a major mental block on it, so I need a little help here! I have an array of 5 integers, the array is already filled with some data. I want to set the last N bits of the array to be random noise. [int][int][int][int][int] eg. set last 40 bits [unchanged][unchanged][unchanged][24 bits of ...

Adding to a bit array

In my program, I am using BitArrays to represent 160 bit numbers. I want to be able to add, subtract, increment and decrement these numbers, what is the algorithm for doing this? At the moment I'm not interested in multiplication and division, but I might be in the future so bonus points for that. I'm implementing in C#, but pseudocode...

Finding the length of the common prefix in two bytes

Given two bytes, how would I find the length of the common bits at the start of the two bytes. For example: 9 == 00001001 6 == 00000110 Common prefix is 0000, length 4 I'm working in C#, so please stick to C# operations only. Addendum: This particular piece of code will run thousands of times and needs to be very fast. ...