If I have, for example:
int32_t x = 572662306; /* 00100010001000100010001000100010 */
I want to store the the two most significant bytes in an int8_t
:
00100010 (base 2) = 34 (base 10)
Or the four most significant bytes in an int16_t
:
0010001000100010 (base 2) = 8738 (base 10)
How can I do this?
That's a very uninteresting number to extract bytes out of. All the bytes are 0x22
. Regardless, here's one way to do it:
#include <stdio.h>
#include <stdint.h>
int main()
{
int32_t num = 572662306;
int8_t num2;
int8_t num3;
int16_t num4;
int16_t num5;
printf("num in hex: 0x%x\n", num);
num2 = (num >> 24);
num3 = (num >> 16);
num4 = (num >> 16);
num5 = num;
printf("num2 in hex: 0x%x\n", num2);
printf("num3 in hex: 0x%x\n", num3);
printf("num4 in hex: 0x%x\n", num4);
printf("num5 in hex: 0x%x\n", num5);
}
Output:
num in hex: 0x22222222 num2 in hex: 0x22 num3 in hex: 0x22 num4 in hex: 0x2222 num5 in hex: 0x2222
PS
You have to be careful about bit-shifting negative numbers. It's better to perform bit shifting on unsigned numbers. If num
is negative, the results of bit shifting to the right is implementation defined. From the C99 standard (6.5.7/5):
The result of
E1 >> E2
isE1
right-shiftedE2
bit positions. IfE1
has an unsigned type or ifE1
has a signed type and a nonnegative value, the value of the result is the integral part of the quotient ofE1 /
2E2. IfE1
has a signed type and a negative value, the resulting value is implementation-defined.