Interpret 4 char as an integer

I have a function that returns n random bytes. For testing, I wanted it to produce 4 random bytes, and then assign 4 bytes of an integer as random bytes. I have something that works, but that seems like an excessive amount of syntax for what I'm trying to do. I just wanted to see if this is really necessary, or if it can be done in a more efficient way.

Note . This runs in xv6 , no solutions relatedinclude

int val0 = (((int)buf[0])&0xff);
int val1 = (((int)buf[1])&0xff);
int val2 = (((int)buf[2])&0xff);
int val3 = (((int)buf[3])&0xff);

int number = val0 | (val1<<8) | (val2<<16) | (val3<<24);
+4
source share
1 answer

, gcc , gcc , , :

union charToInt
{
    char arr[sizeof(int)] ;
    int x ;
} ;

int main()
{
    union charToInt u1 = { .arr = "ab" } ; // or { .arr = "abcd" } if sizeof(int) == 4
}

u1.x int. , , .

+4

All Articles