简体   繁体   English

将unsigned char转换为int和short

[英]Converting unsigned char to int and short

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. 如您所见,此特定函数使用按位运算符将4个unsigned char元素转换为整数。

//Converts a four-character array to an integer, using little-endian form //使用little-endian形式将四字符数组转换为整数

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. 我已经知道按位运算符和char如何使用1个字节,int使用4个字节。 Why would moving char bits 24 bits to the left and than just explicitly converting it to int convert it into an int? 为什么将char位向左移动24位而不是将其显式转换为int将其转换为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. 这可能有一个简单的解释。

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: 假设您有四个8位数字,如下所示:

aaaaaaaa
bbbbbbbb
cccccccc
dddddddd

Shifts give you this: 转移给你这个:

aaaaaaaa000000000000000000000000
00000000bbbbbbbb0000000000000000
0000000000000000cccccccc00000000
000000000000000000000000dddddddd

Bitwise operator OR lets you make a single number from these four parts, because OR -ing any bit x with a zero produces x . 按位运算符OR允许您从这四个部分中生成一个数字,因为将任何位x与零进行OR会产生x If you align four-byte numbers like shown above, there is only one non-zero bit in each position, so bitwise OR s produce the desired result: 如果对齐如上所示的四字节数字,则每个位置只有一个非零位,因此按位OR产生所需的结果:

aaaaaaaabbbbbbbbccccccccdddddddd

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM