Converting unsigned char to int and short

2019-02-17 08:00发布

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.

1条回答
Melony?
2楼-- · 2019-02-17 08:26

Why is bitwise operators necessary for this function?

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:

aaaaaaaa
bbbbbbbb
cccccccc
ffffdffffddd

Shifts give you this:

aaaaaaaa000000000000000000000000
00000000bbbbbbbb0000000000000000
0000000000000000cccccccc00000000
000000000000000000000000ffffdffffddd

Bitwise operator OR lets you make a single number from these four parts, because OR-ing any bit x with a zero produces x. If you align four-byte numbers like shown above, there is only one non-zero bit in each position, so bitwise ORs produce the desired result:

aaaaaaaabbbbbbbbccccccccffffdffffddd
查看更多
登录 后发表回答