これをメモリへのポインタとして、shortsへのポインタとして持っている場合:
unsigned short* ms = reinterpret_cast<unsigned short*>(_memory);
そして、msのサイズ(このショーツの数)を知っているので、これらすべてのショーツとそれらのバイナリ表現を実行してもらいたいと思います。
C ++で各shortのビットにアクセスするにはどうすればよいですか?
タイプの変数のバイナリ表現を表示するには、次のT
ようにします。
template <typename T>
void print_raw(const T & x)
{
const unsigned char * const p = reinterpret_cast<const unsigned char *>(&x);
for (std::size_t i = 0; i != sizeof(T); ++i)
{
if (i != 0) std::putchar(' ');
std::printf("%02X", p[i]);
}
}
あなたはこれをあなたのショーツのリストに差し込むことができます。
printf
(インデックスの2つのルックアップとp[i] / 16
適切p[i] % 16
なアルファベットで置き換えることもできます:
static const char alphabet = "01234567890ABCDEF";
std::putchar(alphabet[p[i] / 16]);
std::putchar(alphabet[p[i] % 16]);
または、純正のバイナリプリンタに交換してください。
void print_byte(unsigned char b)
{
for (std::size_t i = CHAR_BIT; i != 0; --i)
{
std::putchar(b & (1u << (i-1)) ? '1' : '0');
}
}
2つの呼び出しの代わりに、それを前のループにチェーンすることができprintf
ます。)
cout << "\t" << dec << x << "\t\t Decimal" << endl;
cout << "\t" << oct << x << "\t\t Octal" << endl;
cout << "\t" << hex << x << "\t\t Hex" << endl;
cout << "\t" << bitset<MAX_BITS>(x) << endl;
ビットセットを試してください
EDIT(追加コード)
#include <iostream>
#include <bitset>
using namespace std;
int main( int argc, char* argv[] )
{
unsigned short _memory[] = {0x1000,0x0010,0x0001};
unsigned short* ms = reinterpret_cast<unsigned short*>(_memory);
for(unsigned short* iter = ms; iter != ms + 3/*number_of_shorts*/; ++iter )
{
bitset<16> bits(*iter);
cout << bits << endl;
for(size_t i = 0; i<16; i++)
{
cout << "Bit[" << i << "]=" << bits[i] << endl;
}
cout << endl;
}
}
また
#include <iostream>
#include <algorithm>
#include <bitset>
#include <iterator>
int main( int argc, char* argv[] )
{
unsigned short _memory[] = {0x1000,0x0010,0x0001};
unsigned short* ms = reinterpret_cast<unsigned short*>(_memory);
unsigned int num_of_ushorts = 3;//
std::copy(ms, ms+num_of_ushorts, ostream_iterator<bitset<16>>(cout, " "));
}
for (size_t i=0; i<N_SHORTS_IN_BUFFER; i++)
// perform bitwise ops
ここN_SHORTS_IN_BUFFER
で、はのショートパンツの数ですmemory
。
aのビット数short
はですCHAR_BIT * sizeof(short)
。
が16ビットであるという仮定の下で作業している場合はunsigned short
、ビット単位の演算でそれぞれを取得できます。
for( unsigned short* iter = ms; iter != ms + num_of_ushorts; ++iter )
{
int bitN = ( *iter ) & ( 1 << N ); // get the N bit
}
_memory
ショートのリストへのポイントとして、ms
ポインタを配列として使用できます。
unsigned short* ms = reinterpret_cast<unsigned short*>(_memory);
for (int i = 0; i < NUM_SHORTS_IN_MEM; i++)
cout << i << "th element\t" << ms[i] << endl;