C ++ - 将2个char数组元素转换为short int

时间:2013-01-29 20:36:20

标签: c++

我拥有的是这个

char receivedData[27];
short int twoBytes;

我希望twoBytes保留receivedData[14]receivedData[15]的值 意思是,如果receivedData[14]==0x07receivedData[15]==0xBB,则结果为twoBytes=0x07BB

4 个答案:

答案 0 :(得分:3)

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

<< 8表示左移8位(二进制;或2位十六进制),基本上将该值乘以64.这意味着0x0007变为0x0700

|然后会or使用其他值,基本上将其设置为0x07bb

答案 1 :(得分:3)

重要的部分是左移所接收的数据[14] 8位。然后你可以|或+该值到receivedData [15]。重要的是要指出您指定的类型可能会导致问题。使用char数组意味着每个元素至少为8位,如果没有指定unsigned,这可能意味着为符号保留了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 :(得分:2)

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

答案 3 :(得分: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]