转换unsigned char型为int和短 [英] Converting unsigned char to int and short
问题描述
我是新来这个,所以我会说,虽然我一直在寻找对一些code,我意识到,这个功能并不能使意识一位来我做起。
正如你可以看到,这个特定的函数使用位运算符〜4 unsigned char型元素转换为整数。
//四个字符数组转换为整数,使用little-endian的形式
INT toInt(为const char *字节){
回报(INT)(((unsigned char型)字节[3]<< 24)|
((无符号字符)个字节[2]<< 16)|
((无符号字符)字节[1];< 8)|
(无符号字符)字节[0]);
}短toShort(为const char *字节){
返程(短)(((unsigned char型)字节[1];< 8)|
(无符号字符)字节[0]);
}
我已经知道如何按位运算符和char如何使用1个字节和INT使用4个字节。为什么会移动字符位24位的左,不仅仅是明确将其转换为int它转换成一个int? 为什么是必要的这个功能位运算符?
这个功能超出了我的COM prehension,请解释一下这个code和它是如何工作,或者至少给我一个链接,throughly解释这一点。
我到处找的解释,但无法找到它。
这可能有一个很简单的解释。
为什么是必要的这个功能呢?
位运算符
块引用>位运算符是用来从四个单字节数为组装四字节数。
假设你有4个8位数字,如:
AAAAAAAA
BBBBBBBB
CCCCCCCC
DDDDDDDD班次给你这样的:
aaaaaaaa000000000000000000000000
00000000bbbbbbbb0000000000000000
0000000000000000cccccccc00000000
000000000000000000000000dddddddd位运算符
或
可让您在这四个部分单号,因为或
-ing任何位X
以零产生X
。如果您对齐的四字节数如上所示,只有一个非零在每个位置位,所以按位或
我国农产品所需的结果:aaaaaaaabbbbbbbbccccccccdddddddd
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.
解决方案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 dddddddd
Shifts give you this:
aaaaaaaa000000000000000000000000 00000000bbbbbbbb0000000000000000 0000000000000000cccccccc00000000 000000000000000000000000dddddddd
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:aaaaaaaabbbbbbbbccccccccdddddddd
这篇关于转换unsigned char型为int和短的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!