私が持っているのはこれです
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進数または2桁の16進数)で、基本的に値を64倍することを意味します。これは、0x0007
になることを意味します0x0700
。
|
次に、or
これを他の値と組み合わせて、基本的にに設定し0x07bb
ます。
重要な部分は、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));
お役に立てば幸いです。
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]