I am new to this, so I will begin by saying that while I was looking over some code I realized that this function doesn't make one bit of sense to me.
As you can see that this specific function uses bitwise operators to convert 4 unsigned char elements into integer.
//Converts a four-character array to an integer, using little-endian form
int toInt(const char* bytes) {
return (int)(((unsigned char)bytes[3] << 24) |
((unsigned char)bytes[2] << 16) |
((unsigned char)bytes[1] << 8) |
(unsigned char)bytes[0]);
}
short toShort(const char* bytes) {
return (short)(((unsigned char)bytes[1] << 8) |
(unsigned char)bytes[0]);
}
I already know how bitwise operators and how char uses 1 byte and int uses 4 bytes. Why would moving char bits 24 bits to the left and than just explicitly converting it to int convert it into an int? Why is bitwise operators necessary for this function?
This function goes beyond my comprehension, please explain this code and how it works or at least give me a link that throughly explains this.
I have looked everywhere for the explanation but could not find it.
This probably has a simple enough explanation.
Bitwise operators are used to "assemble" the four-byte number from four single-byte numbers.
Let's say you've got four 8-bit numbers, like this:
Shifts give you this:
Bitwise operator
OR
lets you make a single number from these four parts, becauseOR
-ing any bitx
with a zero producesx
. If you align four-byte numbers like shown above, there is only one non-zero bit in each position, so bitwiseOR
s produce the desired result: