-2

I want use a define to get the 4 bytes from an int. How should I write this define?

int k = 4;
unsigned char byteK[4];

byteK[0] = (unsigned char)k & 0xFF;
byteK[1] = (unsigned char)((k >> 8) & 0xFF);
byteK[2] = (unsigned char)((k >> 16) & 0xFF);
byteK[3] = (unsigned char)((k >> 24) & 0xFF);
Lundin
  • 195,001
  • 40
  • 254
  • 396
Ken Chu
  • 137
  • 11

1 Answers1

0

Do you mean something like that (assuming that int on your machine is really 4 bytes):

#define INT_TO_4BYTE_ARRAY(int_var) ((unsigned char *)(&int_var))

and then you can use it like this:

int new_var = 0x11223344;

unsigned char byte0 = INT_TO_4BYTE_ARRAY(new_var)[0];
unsigned char byte1 = INT_TO_4BYTE_ARRAY(new_var)[1];
unsigned char byte2 = INT_TO_4BYTE_ARRAY(new_var)[2];
unsigned char byte3 = INT_TO_4BYTE_ARRAY(new_var)[3];

On my machine (little endian) I get:

byte0=0x44 byte1=0x33 byte2=0x22 byte3=0x11

Alex Lop.
  • 6,810
  • 1
  • 26
  • 45
  • Remember that you'll need to write two (or more) versions of this, one for each endianness of your target platforms. – Toby Speight Sep 02 '15 at 07:21
  • @TobySpeight, not me but @KenChu. Two for each endianness, one for `sizeof(int) == 2` and one for `sizeof(int)==4`. But if he needs it for some local task which is not a product or not going to be ported to other platforms then he may use only the one working version. – Alex Lop. Sep 02 '15 at 07:38
  • thank you so much, Alex Lop. that's what I need. but if it possible be #define INT32_TO_4BYTE_ARRAY(int_var) {}, then return an unsigned char array[4], like unsigned char *temp = INT32_TO_4BYTE_ARRAY(int_var), and then I can get the byte value from temp – Ken Chu Sep 02 '15 at 16:53
  • @KenChu, sorry, could you clarify what exactly do you want to define? – Alex Lop. Sep 02 '15 at 16:56
  • @Alex Lop. like unsigned char *temp = INT32_TO_4BYTE_ARRAY(int_var), and then temp[0] = 0x44, temp[1] = 0x33, .... – Ken Chu Sep 02 '15 at 17:03
  • @KenChu, yes, of course. You can use it that way too. – Alex Lop. Sep 02 '15 at 17:19
  • when I use unsigned char *temp = INT32_TO_4BYTE_ARRAY(int_var), I got return of memory address of int_var. – Ken Chu Sep 02 '15 at 17:37
  • @KenChu that's true, but now you treat it as `unsigned char arr[4]`. – Alex Lop. Sep 02 '15 at 17:38
  • @AlexLop. how to treat it as unsigned char arr[4], if I use unsigned char *temp = INT32_TO_4BYTE_ARRAY(int_var), it's same with unsigned char *temp = &int_var. how can I access temp[x] directly. sorry, I am not good in c language – Ken Chu Sep 03 '15 at 01:37
  • @KenChu you can use `unsigned char *` as an array. It is the same. The C language allows it. – Alex Lop. Sep 03 '15 at 03:23
  • @AlexLop. but if I get the value from temp[x], I get unpredicted value. not the byte value of int_var. – Ken Chu Sep 03 '15 at 05:07
  • @KenChu it is perfectly defined as long as `x` is less than 4. – Alex Lop. Sep 03 '15 at 05:18