简体   繁体   中英

How can I extract blocks of Bytes from a int32_t and store it in a int16_t or int8_t using c?

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 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 / 2 E2 . If E1 has a signed type and a negative value, the resulting value is implementation-defined.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM