[英]Convert char byte to integer value
For example , 130ABF (Hexadecimal) is equals to 1247935 (Decimal), So my byte array is 例如, 130ABF (十六进制)等于1247935 (十进制),所以我的字节数组是
char buf[3] = {0x13 , 0x0A , 0xBF};
and I need to retrieve the decimal value from the byte array. 我需要从字节数组中检索十进制值。
Below are my sample code: 以下是我的示例代码:
#include<iostream>
using namespace std;
int main()
{
char buf[3] = {0x13 , 0x0A , 0xBF};
int number = buf[0]*0x10000 + buf[1]*0x100 + buf[2];
cout<<number<<endl;
return 0;
}
and the result is : (Wrong) 结果是:(错误)
1247679
Unless I change the 除非我改变
char buf[3] = {0x13 , 0x0A , 0xBF};
to 至
int buf[3] = {0x13 , 0x0A , 0xBF};
then It will get correct result. 那么它将得到正确的结果。
Unfortunately, I must set my array as char type, anyone know how to solve this ? 不幸的是,我必须将数组设置为char类型,有人知道如何解决这个问题吗?
Define the array as: 将数组定义为:
unsigned char buf[3];
Remember that char could be signed. 请记住,可以对char进行签名。
UPDATE: In order to complete the answer, it is interesting to add that "char" is a type that could be equivalent to "signed char" or "unsigned char", but it is not determined by the standard. 更新:为了完成答案,有趣的是添加了“ char”是可以等同于“ signed char”或“ unsigned char”的类型,但是它不是由标准确定的。
Array elements will be promouted to int
before evaluating. 数组元素将在评估前提升为int
。 So if your compiler treats char
as signed you get next (assuming int
is 32-bit): 因此,如果您的编译器将char
视为带符号,则会得到下一个(假设int
是32位):
int number = 19*0x10000 + 10*0x100 + (-65);
To avoid such effect you can declare your array as unsigned char arr[]
, or use masking plus shifts: 为了避免这种影响,您可以将数组声明为unsigned char arr[]
,或使用masking + shifts:
int number = ((buf[0] << 16) & 0xff0000)
| ((buf[1] << 8) & 0x00ff00)
| ((buf[2] << 0) & 0x0000ff;
Since your char array is signed, when you want to initialize the last element ( 0xBF
), you are trying to assign 191 to it while the max it can store is 127: a narrowing conversion occurs... A workaround would be the following: 由于您的char数组已签名,因此当您要初始化最后一个元素( 0xBF
)时,您尝试为其分配191,而它可以存储的最大值是127:发生缩小转换...解决方法如下:
unsigned char[3] = { 0x13, 0x0A, 0xBF };
This will prevent the narrowing conversion. 这将防止缩小转换。 Your compiler should have given you a warning about it. 您的编译器应该已经对此发出警告。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.