1

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?

reuben
  • 3,360
  • 23
  • 28
  • What have you tried? Do you know about the bitwise and shift operators? 4-bit bytes aren't supported by standard C, either. Do you mean nibble? – Carl Norum Mar 23 '15 at 03:11

1 Answers1

0

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 is E1 right-shifted E2 bit positions. If E1 has an unsigned type or if E1 has a signed type and a nonnegative value, the value of the result is the integral part of the quotient of E1 /2E2. If E1 has a signed type and a negative value, the resulting value is implementation-defined.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • 1
    to be a little bit pedantic: you should use unsigned types, otherwise you can get unexpected output if one of the MSBs is set: https://ideone.com/eQ8fsL – mch Mar 23 '15 at 09:12