Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How convert unsigned int to unsigned char array

Tags:

c++

c

I just need to extract those bytes using bitwise & operator. 0xFF is a hexadecimal mask to extract one byte. For 2 bytes, this code is working correctly:

#include <stdio.h>

int main()
{
    unsigned int i = 0x7ee;
    unsigned char c[2];

    c[0] = i & 0xFF;
    c[1] = (i>>8) & 0xFF;

    printf("c[0] = %x \n", c[0]);
    printf("c[1] = %x \n", c[1]);


    return 0;
}

output:

c[0] = ee;
c[1] = 7;

What should I do for 4 bytes to work correctly?

unsigned int i = 0x557e89f3;
unsigned char c[4];

my code:

unsigned char c[4];
         c[0] = i & 0xFF;
         c[1] = (i>>8) & 0xFF;
         c[2] = (i>>16) & 0xFF;
         c[3] = (i>>24) & 0xFF;
         printf("c[0] = %x \n", c[0]);
         printf("c[1] = %x \n", c[1]);
         printf("c[2] = %x \n", c[2]);
         printf("c[3] = %x \n", c[3]);

2 Answers

#include <stdio.h>

int main()
{
    unsigned int i = 0x557e89f3;
    unsigned char c[4];

    c[0] = i & 0xFF;
    c[1] = (i>>8) & 0xFF;
    c[2] = (i>>16) & 0xFF;
    c[3] = (i>>24) & 0xFF;

    printf("c[0] = %x \n", c[0]);
    printf("c[1] = %x \n", c[1]);
    printf("c[2] = %x \n", c[2]);
    printf("c[3] = %x \n", c[3]);


    return 0;
}
like image 172
Seema Kadavan Avatar answered Apr 28 '26 20:04

Seema Kadavan


First of all. It is not guaranteed by C standard that 'unsigned int' is 32-bit-long. To ensure it you should use uint32_t type defined in stdint.h header (C99). However, implementation of this type is not mandatory. Other solution is to use 'unsigned long' that is guaranteed to have at least 32 bits.So the solutions should be:

#include <stdio.h>

int main()

{
    unsigned long int i = 0x557e89f3UL;
    unsigned char c[4];

    c[0] = i & 0xFF;
    c[1] = (i>>8) & 0xFF;
    c[2] = (i>>16) & 0xFF;
    c[3] = (i>>24) & 0xFF;

    printf("c[0] = %x \n", c[0]);
    printf("c[1] = %x \n", c[1]);
    printf("c[2] = %x \n", c[2]);
    printf("c[3] = %x \n", c[3]);


    return 0;
}
like image 31
tstanisl Avatar answered Apr 28 '26 21:04

tstanisl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!