I didn't think I'd 'lose out on the chance' by not answering this one right
away. :)

> data[dataLength] = (uint) (value & 0xFFFFFFFF);
> data[maxLength-1] & 0x80000000

These are both examples of what they call 'bit masking'. It's used to gain
access to only the data of interest in a given operation. Generally, when
dealing with bitwise operations, it's good to change the item to binary to
understand.

As a quick guide to those who might be confused about the whole thing,
'recall' the following:

0b0 & 0b0 == 0b0
0b0 & 0b1 == 0b0
0b1 & 0b0 == 0b0
0b1 & 0b1 == 0b1

In other words, the bit has to be 1 in both places to be 1 in the result.

> data[dataLength] = (uint) (value & 0xFFFFFFFF);
becomes
> data[dataLength] = (uint) (value & 0b11111111111111111111111111111111);

In this example, it's 'obvious' (without knowing the declaration) that
'value' can be much larger than needed.
It's also 'obvious' that only the lower 32 bits are important to the
program, so a bitwise AND with all 1s means
that any 1 in the lower 32 bits is preserved, whereas any LARGER ones are
ignored (as they are bitwise ANDed
with 0).

> data[maxLength-1] & 0x80000000
becomes
> data[maxLength-1] & 0b10000000000000000000000000000000

In this case, we're only concerned with ONE bit in the last element in the
array. The rest don't matter, obviously. So this
operation masks off all the rest of the 'not important bits'.

Also what happens if you bit shift 32 bits on a number like -1. How do
> I calculate the right/left shift on a certain number. Is there a
> formula I need to understand.
>
> Generally, all you need to understand is the binary representation of the
number, and then you should be fine in understanding bitwise operations. A
left shift on a number is equivalent to multiplying by 2; a right shift,
dividing by 2 and ignoring the remainder. But it depends on how many bits
the representation is, and how (if at all) it's masked afterwards. It also
matters if a number is 'signed' or 'unsigned', as 'signed' numbers store the
sign as a '1' in the leftmost bit.

http://www.vipan.com/htdocs/bitwisehelp.html is a nice link for research,
but he's a Java programmer. :)
http://www.dreamincode.net/forums/showtopic103051.htm is an interesting
discussion in a .NET-oriented forum.

Reply via email to