4

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

Note: This is being done in xv6, no solutions that involve an include

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);
Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
asimes
  • 5,749
  • 5
  • 39
  • 76

1 Answers1

4

As far as I can see you are using gcc from this reference here and we know gcc support type punning through unions explicitly then that may be a reasonable solution:

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

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

Then u1.x will hold the the int value. I did not add any output since I am not sure what you use for output.

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740