I am receiving signed value having 8 bytes to byte buffer[8]. This sign bit is bit 63 for all value.
This value doesnt need so big range, the 4 most significant bytes are zero. But I need the sign.
How can I retype this value to standart signed long(4 Bytes)?
Sign is in bit 63, so
signed char my_sign = buffer[7] & 0x80 ? -1 : 0
give me the sign (buffer[0] & 0x80 ? -1 : 0 for th开发者_如何学编程e other Indian :-)
The value than
signed long my_value = my_sign ? -*(long *)buffer : *(long *)buffer
Is there simpler way?
Assuming big-endian, and that you only want the sign, i.e. your output is -1 or 0:
long my_value = buffer[1] & 0x80 ? -1 : 0
I feel the urge for ASCII graphics to enhance the understandability of the above. Here's how I assumed the bits to be numbered, inside buffer
:
6666555555555544444444443333333333222222222211111111110000000000 (tens) 3210987654321098765432109876543210987654321098765432109876543210 (ones) [000000][111111][222222][333333][444444][555555][666666][777777] (bytes)
So, if you read vertically through the two top lines (tens and ones), at the column that forms "47" (bolded), you hit the left bracket for the byte with index 2. Since the brackets mark the most and least significant bits, that means you've hit the MSB of the byte at index 2. This bit has index 7 inside the byte, meaning the mask for it is 1 << 7, or 128, or 0x80.
Thus, the bit is tested with the expression buffer[2] & 0x80
.
What representation is used for negative numbers in your 8 byte value? If it used 2's-complement, then you can rely on the fact that 2's-complement values can be safely truncated to any length without doing any extra steps. The original value is preserved as long as you are not truncating any "occupied" positions.
I.e. positive 8-byte value will have all-zeroes in higher "unused" bytes, while negative value will have all-ones in higher "unused" bytes. Depending on byte ordering, it is possible that you don't need to do anything: just take the lower 4 bytes and you are done.
So, again, what representation is used for negative numbers? You said that higher-order bytes contain zeros. Are we supposed to assume that they contain zeros even for negative numbers? If so, then the representation used is not 2's-complement.
Negative numbers are stored in 2's complement this means that 64bit -1 = 0xFFFFFFFFFFFFFFFF. If you just pick out the 32 least significant bits you have 0xFFFFFFFF = -1. So assuming you are dealing with numbers that are in the 32 bit range should should be able to treat positive and negative numbers in exactly the same way.
精彩评论