C++ - 将两个字符数组元素转换为短整型

3

我所拥有的是这个

char receivedData[27];
short int twoBytes;

我希望twoBytes存储receivedData[14]receivedData[15]的值,也就是说,如果receivedData[14]==0x07receivedData[15]==0xBB,则结果应为twoBytes=0x07BB


1
receivedData[14] * 256 + receivedData[15] 怎么样? - Bo Persson
1
请使用unsigned char来定义您的缓冲区,以避免出现意想不到的问题。 - Simon Richter
4个回答

5

twoBytes = receivedData[14] << 8 | receivedData[15];

<< 8表示左移8位(二进制;或2个十六进制数字),本质上是将值乘以64。这意味着0x0007变成了0x0700

|然后将其与另一个值进行or,本质上将其设置为0x07bb


1
<< 8 //左移8位,不是2位。 - Joel Rondeau
是的,打字太快了。;) - Mario

3

重要的部分是将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);
}

您可以通过以下方式检查特定类型的大小: printf(“%zu \ n”,sizeof(char));
希望能帮到您。

2
Just use logical operators
twoBytes=receivedData[14]; //twobytes=07h
twoBytes=twoBytes<<8; //twobytes=0700h
twoBytes|=receivedData[15]; //twobytes=07BBh

1

我不确定你的应用程序,但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]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接