I am having a problem assigning bits a value of 0. The data is a 16 bit integer the bits greater than the 12th bit have garbage either a 0 or a 1. I would like to assign all bits greater than 12th bit the value 0 no matter what their values are. Whats the best approach.
if (number ^ (1 << 15 - k) < number)
{
// yes it is
number ^= (1 << 15 - k); // unset the bit
}
To assign all bits greater than 12th the value 0, it is easier than using a for-loop and applying the above method. You can instead set a mask value and use both bitiwse or and bitwise xor:
1 2 3
unsigned mask = 15;
number |= mask; // turn on all bits from 12th ->
number ^= mask; // turn off all bits from 12th ->
So are you saying that the bits 0 - 11 are greater than the 12th bit? I want to understand this endian business
I'm saying the opposite.
Bit 11 is the 12th bit (because bit 0 would be the "first" bit). As a general rule, I try to avoid "Nth" phrasing when dealing with 0 based numbers to avoid confusion.
Bit 12 would be more significant (aka, "greater") than bit 11.
Also your method will not unset any bits that are already set
My method will unset all bits 12 and greater, regardless of what their original value was. bits 0 through 11 would remain unchanged. Bitwise AND in action:
There are two schemes of bit numbering - LSB 0 and MSB 0. Both are widely used.
I don't doubt you... but personally I have never seen bit 0 refer to the MSB in my entire life. Probably because most/all of my experience has come from low level hardware register descriptions, binary file format descriptions, C/C++ libraries, and the like.
I've never gone into networking protocols, so I believe you when you say it's commonplace there. It just doesn't seem to be commonplace anywhere else.