Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems with byte-reversing an integer

Tags:

c

endianness

Godday all.

Could someone please explain the logical difference in these two implementations of a byte-reversing function.

Example 1:

uint32_t byte_reverse_32(uint32_t num) {
    static union bytes {
        uint8_t b[4];
        uint32_t n;
    } bytes;
    bytes.n = num;

    uint32_t ret = 0;
    ret |= bytes.b[0] << 24;
    ret |= bytes.b[1] << 16;
    ret |= bytes.b[2] << 8;
    ret |= bytes.b[3];

    return ret;
}  

Example 2:

uint32_t byte_reverse_32(uint32_t num) {
    static union bytes {
        uint8_t b[4];
        uint32_t n;
    } bytes;
    bytes.n = num;

    uint32_t ret = 0;
    ret |= (bytes.b[0] << 24) || (bytes.b[1] << 16) || (bytes.b[2] << 8) || (bytes.b[3]);
    return ret;
}

I must be missing something because for the unsigned integer 0xFE12ADCF the first example correctly gives 0xCFAD12FE while the second one yields 1. What am I missing?

By the way, I couldn't figure out how to get '<<' inside the pre+code-tags, hence LSHIFT. If it's possible to do it, feel free to edit (and comment on how =)).

Thanks.

EDIT: Fixed the bytes-variable which was never assigned to.

like image 394
manneorama Avatar asked Jan 22 '26 01:01

manneorama


1 Answers

| is not the same operator as ||. The first is a bitwise OR, which is what you want. The second is a boolean OR, which is what you have.

like image 131
Nabb Avatar answered Jan 23 '26 19:01

Nabb



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!