Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the point of bitwise and-ing with 255 when using bitshifting method of bytes reordering?

There is an article, explaining little/big-endian topic, and it contains an example of endianness conversion function:

short reverseShort (short s) {
    unsigned char c1, c2;

    if (is_bigendian()) {
        return s;
    } else {
        c1 = s & 255;
        c2 = (s >> 8) & 255;

        return (c1 << 8) + c2;
    }
}

I understand, why they and-ing here:

c1 = s & 255;

255 = 11111111, so bitwise and with s which may be like 1011011010010010, will not affect numbers in last 8 places, but turn all leading places to zeroes. So it's cuts bits to ending 8.

I also understand, why they using right shift here:

c2 = (s >> 8) & 255;

Shift by 8 cuts last 8 bits, so leading 8 remains. So in the first operation they get last 8 bits, and then first 8 bits.

But why they 'and'-ing it with 255 again?

like image 579
Gill Bates Avatar asked Dec 05 '25 02:12

Gill Bates


1 Answers

lets say s = binary representation: abcdefghijklmnopqrst

c1 = s & 255; // < mnopqrst first 8 bits
c2 = (s >> 8) & 255;  //    from abcdefghijklmnopqrst >> 8 = abcdefghijkl & b11111111 = efghijkl

return (c1 << 8) + c2; // < (mnopqrst00000000) + efghijkl = mnopqrstefghijkl

its essentially taking the first 8 bits, and the next 8, then reverses them

But why they 'and'-ing it with 255 again?

Thats to truncate it down to 8 bits if its longer

like image 188
maksymiuk Avatar answered Dec 06 '25 15:12

maksymiuk



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!