I'm really new to coding (as in started about 1.5 weeks ago), so hopefully, my asking this here isn't too heinous a crime (and if it is, I beg forgiveness).
I'm trying to write a function that counts the bits in an integer and the code I've written seems to work perfectly for counting positive integers, but negative integers seem to act really funny.
From what I had learned, I was under the impression that a negative signed integer just had a bit set out in front of it like the following example:
2: 0000 0010
-2: 1000 0010
So ideally my function should act like so: bit_count([negative number here])
is the same as 1 + bit_counter([absolute value of negative number])
But it doesn't.
Here's my function:
int bit_count(int byte)
{
int bit;
int tally;
tally = 0;
for (bit = 0x80; bit > 0; bit = bit >> 1)
{
if ((byte & bit) != 0)
++tally;
}
return (tally);
}
Some sample data:
bit_count(-1)
results in 8
bit_count(-6)
results in 6
bit_count(-4)
results in 6
and so on...
I had a friend that I have quite a bit of trust suggest that depending on the machine, there was actually more metadata in front of the signed bit that my bit counting function was including, but I don't know what I'd need to do to correct for that.
Thanks
As others have pointed out in the comments, although it is valid to check the most significant bit when determining the sign of an signed integer, the rest of the byte changes as well.
In other words, your code is working correctly, but your premise about the representation of negative integers is wrong.
The mechanism used in signed ints is called two's complement and essentially means taking 2^n, where n is the number of bits, and subtracting the absolute value of the integer to get its negative value.
-2 is therefore
1111 1110
and not
1000 0010
as you would expect. The reason for this is that it ensures that standard arithmetical operations work for signed ints.