[英]Convert some bytes from a unsigned char to int
I want to convert some bytes to an int. 我想将一些字节转换为整数。 This is my code so far: 到目前为止,这是我的代码:
unsigned char *bytePtr = (unsigned char *)[aNSDataFrame];
I want to take 4 bytes from this unsigned char: myFrame[10]
, myFrame[11]
, myFrame[12]
and myFrame[13]
and convert them to an integer. 我想从这个无符号字符中myFrame[10]
4个字节: myFrame[10]
, myFrame[11]
, myFrame[12]
和myFrame[13]
并将它们转换为整数。
int bytesToInt(unsigned char* b, unsigned length)
{
int val = 0;
int j = 0;
for (int i = length-1; i >= 0; --i)
{
val += (b[i] & 0xFF) << (8*j);
++j;
}
return val;
}
you can do, 你可以做,
int a;
a=myframe[10];
a=a<<8;
a=a|myframe[11];
a=a<<8;
a=a|myframe[12];
a=a<<8;
a=a|myframe[13];
this will create integer containing those bytes 这将创建包含这些字节的整数
int val = *(const int*)&myFrame[10];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.