I have a small issue that I can't seem to figure out, so I thought that I would run it by all of you.
The highest order bit in a byte has a value of 128.
From my understanding, signed numeric data types use this bit to tell the number if it is positive or negative.
In an int, there are 4 bytes, which multiplied by 8, gives you how many bits there are in an int.
well...if you shift 128 to the left by the number of bytes in an int, and subtract 1, then multiply by 8, wouldn't you have the highest order bit of an integer?
Example: ( 128 << ((sizeof(int) - 1) * 8) ) : (128 << 24)
I also tried (128 << ((sizeof(int)) * 8)) : (128 << 32)
in order to isolate the bit, just in case my reasoning was flawed.
In order to obtain the absolute value though, I took that bit, and ANDed it with the value of my int, and then XORed it, to try and obtain the absolute value....
Example:
(1000 0010)Code:byte value = -2;
128 or -0Code:byte highbit = (128 << ((sizeof(byte) - 1) * 8));
1000 0010 //valueCode:byte valueHighbit = highbit & value;
1000 0000 //highbit
-----------------------
1000 0000 //tells us the highbit is on in the value
1000 0000 //valueHighbit;Code:byte result = valueHighbit ^ value;
1000 0010 //value;
------------------------------
0000 0010 //result
So as you can see, the result should be positive 2.
However, if you try this, you will see it is not...Why is this?
Why does this particular approach not work? Is it the way in which I am trying to obtain the highest bit? I can do this with various other methods, but I wanted to know why this one appears to be incorrect. Please educate me!