5

私は を持っていて、最初の 4 つの要素にvector<unsigned char>4 バイトを入れたいと思っています。Integer次のようなマスキングよりも C++ で簡単な方法はありますか。

myVector.at(0) = myInt & 0x000000FF;
myVector.at(1) = myInt & 0x0000FF00;
myVector.at(2) = myInt & 0x00FF0000;
myVector.at(3) = myInt & 0xFF000000;
4

5 に答える 5

4

これを機能させるには、値をバイナリシフトする必要があります。

myVector.at(0) = (myInt & 0xFF);
myVector.at(1) = (myInt >> 8) & 0xFF;
myVector.at(2) = (myInt >> 16) & 0xFF;
myVector.at(3) = (myInt >> 24) & 0xFF;

あなたのコードは間違っています:

int myInt = 0x12345678;
myVector.at(0) = myInt & 0x000000FF; // puts 0x78 
myVector.at(1) = myInt & 0x0000FF00; // tries to put 0x5600 but puts 0x00
myVector.at(2) = myInt & 0x00FF0000; // tries to put 0x340000 but puts 0x00
myVector.at(3) = myInt & 0xFF000000; // tries to put 0x12000000 but puts 0x00
于 2013-06-04T08:23:35.533 に答える
1

最もコンパクトな方法は次のとおりです。

myVector.at(0) = *((char*)&myInt+0);
myVector.at(1) = *((char*)&myInt+1);
myVector.at(2) = *((char*)&myInt+2);
myVector.at(3) = *((char*)&myInt+3);
于 2013-06-04T08:54:07.737 に答える