我所拥有的是这个
char receivedData[27];
short int twoBytes;
我希望twoBytes
存储receivedData[14]
和receivedData[15]
的值,也就是说,如果receivedData[14]==0x07
且receivedData[15]==0xBB
,则结果应为twoBytes=0x07BB
我所拥有的是这个
char receivedData[27];
short int twoBytes;
我希望twoBytes
存储receivedData[14]
和receivedData[15]
的值,也就是说,如果receivedData[14]==0x07
且receivedData[15]==0xBB
,则结果应为twoBytes=0x07BB
twoBytes = receivedData[14] << 8 | receivedData[15];
<< 8
表示左移8位(二进制;或2个十六进制数字),本质上是将值乘以64。这意味着0x0007
变成了0x0700
。
|
然后将其与另一个值进行or
,本质上将其设置为0x07bb
。
重要的部分是将receivedData[14]左移8位。然后可以将该值与receivedData[15]进行|或+运算。需要指出的是,您指定的类型可能会引起问题。使用char数组意味着每个元素至少有8位,而不指定无符号可能意味着1位被保留为符号位。更大的问题是,char不能保证为8位,它可能更大。对于short int也是如此,该值至少为16位,但可能更大。此外,您应该使用unsigned short int。最好使用stdint.h,这样您可以精确控制变量大小:
#include <stdio.h>
#include <stdint.h>
main() {
uint8_t receivedData[27];
uint16_t twoBytes;
receivedData[14] = 0x07;
receivedData[15] = 0xBB;
twoBytes = receivedData[14] << 8;
twoBytes = twoBytes | receivedData[15];
printf("twoBytes %X\n", twoBytes);
}
Just use logical operators
twoBytes=receivedData[14]; //twobytes=07h
twoBytes=twoBytes<<8; //twobytes=0700h
twoBytes|=receivedData[15]; //twobytes=07BBh
我不确定你的应用程序,但receivedData
听起来像是来自另一台计算机的数据,这可能是使用ntohx
的情况:
#include <iostream>
#include <cstdint>
#include <iomanip>
#include <arpa/inet.h>
int main() {
uint8_t receivedData[27] {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0xBB,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00 };
{
// The ugly way.
// You have to be sure that the alignment works.
uint16_t const twoBytes {
ntohs( *reinterpret_cast<uint16_t*>( &receivedData[14] ) ) };
std::cout << "TB [" << std::hex << twoBytes << "]" << std::endl;
}
{
// The union way
union {
uint8_t rd[2];
uint16_t s;
};
rd[0] = receivedData[14]; rd[1] = receivedData[15];
uint16_t const twoBytes { ntohs( s ) };
std::cout << "TB [" << std::hex << twoBytes << "]" << std::endl;
}
return 0;
}
输出:
TB [7bb]
TB [7bb]
receivedData[14] * 256 + receivedData[15]
怎么样? - Bo Perssonunsigned char
来定义您的缓冲区,以避免出现意想不到的问题。 - Simon Richter