Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple bitwise manipulation for little-endian integer, in big-endian machine?

For a specific need I am building a four byte integer out of four one byte chars, using nothing too special (on my little endian platform):

    return (( v1 << 24) | (v2 << 16) | (v3 << 8) | v4);

I am aware that an integer stored in a big endian machine would look like AB BC CD DE instead of DE CD BC AB of little endianness, although would it affect the my operation completely in that I will be shifting incorrectly, or will it just cause a correct result that is stored in reverse and needs to be reversed?

I was wondering whether to create a second version of this function to do (yet unknown) bit manipulation for a big-endian machine, or possibly to use ntonl related function which I am unclear of how that would know if my number is in correct order or not.

What would be your suggestion to ensure compatibility, keeping in mind I do need to form integers in this manner?

like image 835
Alexander Avatar asked Dec 13 '22 14:12

Alexander


1 Answers

As long as you are working at the value level, there will be absolutely no difference in the results you obtain regardless of whether your machine is little-endian or big-endian. I.e. as long as you are using language-level operators (like | and << in your example), you will get exactly the same arithmetical result from the above expression on any platform. The endianness of the machine is not detectable and not visible at this level.

The only situations when you need to care about endianness is when the data you are working with is examined at the object representation level, i.e. in situations when its raw memory representation is important. What you said above about "AB BC CD DE instead of DE CD BC AB" is specifically about the raw memory layout of the data. That's what functions like ntonl do: they convert one memory layout to another memory layout. So far you gave no indication that the actual raw memory layout is in any way important to you. Is it?

Again, if you only care about the value of the above expression, it is fully and totally endianness-independent. Basically, you are not supposed to care about endianness at all when you write C programs that don't attempt to access and examine the raw memory contents.

like image 74
AnT Avatar answered Jan 04 '23 23:01

AnT