3

私が持っているのはこれです

char receivedData[27];
short int twoBytes;

私が欲しいのはtwoBytes、の値receivedData[14]receivedData[15] 意味を保持することです。との場合receivedData[14]==0x07receivedData[15]==0xBB結果は次のようになります。twoBytes=0x07BB

4

4 に答える 4

5

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

<< 8は、左シフトを8桁(2進数または2桁の16進数)で、基本的に値を64倍することを意味します。これは、0x0007になることを意味します0x0700

|次に、orこれを他の値と組み合わせて、基本的にに設定し0x07bbます。

于 2013-01-29T20:38:13.787 に答える
3

重要な部分は、receivedData[14]8ビットを左シフトすることです。次に、次のいずれかを行うことができます| または+その値をreceivedData[15]に。指定したタイプが問題を引き起こす可能性があることを指摘することが重要です。char配列を使用するということは、各要素が少なくとも8ビットであることを意味し、unsignedを指定しない場合、これは1ビットが符号用に予約されていることを意味します。より大きな懸念は、charが8ビットであることが保証されていないことです。それはもっと大きくなる可能性があります。同じことがshortintにも当てはまります。この値は、少なくとも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));

お役に立てば幸いです。

于 2013-01-29T21:47:41.507 に答える
2
Just use logical operators
twoBytes=receivedData[14]; //twobytes=07h
twoBytes=twoBytes<<8; //twobytes=0700h
twoBytes|=receivedData[15]; //twobytes=07BBh
于 2013-01-29T20:39:29.990 に答える
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]
于 2013-01-29T21:02:06.707 に答える