Convert unsigned char to int and short

I am new to this, so I will start by saying that while I was looking through some code, I realized that this function does not make any sense to me.

As you can see, this particular function uses bitwise operators to convert four unsigned char elements to an integer.

// Converts a four-character array to an integer using a small-end 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 move char bits to 24 bits to the left and than just explicitly convert it to int, convert it to int? Why are bitwise operators necessary for this function?

This function is beyond my understanding, explain this code and how it works, or at least give me a link that explains this.

I searched everywhere for an explanation, but could not find it.

This is probably a fairly simple explanation.

+6
source share
1 answer

Why are bitwise operators necessary for this function?

Bitwise operators are used to "assemble" a four-byte number from four single-byte numbers.

Say you have four 8-bit numbers, for example:

 aaaaaaaa bbbbbbbb cccccccc dddddddd 

Shifts give you the following:

 aaaaaaaa000000000000000000000000 00000000bbbbbbbb0000000000000000 0000000000000000cccccccc00000000 000000000000000000000000dddddddd 

The bitwise OR operator allows you to make one number from these four parts, because OR - in any bit x with a zero value generates x . If you align four-byte numbers as shown above, there is only one non-zero bit in each position, so a bitwise OR creates the desired result:

 aaaaaaaabbbbbbbbccccccccdddddddd 
+6
source

Source: https://habr.com/ru/post/978535/


All Articles