Search code examples
arrayscharunionlong-integerunsigned

Using a union to read a char array as an unsigned long int


As the title hints, essentially I convert a char array into an unsigned long int (or rather, read as an unsigned long int) by means of a Union.

union {
    char buffer[8];
    unsigned long int buffer_ui;
} char_array_ui;

I read 8 chars into the char array, then later on return the value of those 8 chars as an unsigned long int. (For those curious, it is because I am reading chars from /dev/urandom). Is this safe to do? Is there anything that could potentially go in my program?


Solution

  • 2 things to be aware of:

    • It's correct as long as the size of unsigned long is 8 bytes - might not be so on every platform.
    • Endianness might be different on various platforms, thus producing different results. If you read data as an unsigned long it's automatically taken care of to produce the correct result but if you read it byte after byte, the order is the way you store the bytes.