如果我将它作为指向内存的指针作为指向短裤的指针:
unsigned short* ms = reinterpret_cast<unsigned short*>(_memory);
而且我知道 ms 的大小(这条短裤的数量),我希望看到所有这些短裤及其二进制表示形式的运行。
如何访问 C++ 中每个短路的位?
要查看任何类型变量的二进制表示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
用两个索引查找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');
}
}
您可以将其链接到前一个循环而不是两个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;
尝试通过位集
编辑(添加代码)
#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, " "));
}
作为_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;
If you are working under the assumption that an unsigned short
has 16 bits, then you can retrieve each of them with bitwise operations:
for( unsigned short* iter = ms; iter != ms + num_of_ushorts; ++iter )
{
int bitN = ( *iter ) & ( 1 << N ); // get the N bit
}
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)
。