如何查看short的位表示?

时间:2011-11-15 20:43:31

标签: c++ bit short

如果我把它作为指向内存的指针作为指向短路的指针:

unsigned short* ms = reinterpret_cast<unsigned short*>(_memory);

我知道ms的大小(这个短裤的数量),我希望看到所有这些短片及其二进制表示。

如何在C ++中访问每个short的位?

5 个答案:

答案 0 :(得分:4)

要查看类型为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]);
  }
}

您可以将其插入短片列表中。

(您甚至可以用合适的字母表中的两个索引printfp[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调用。)

答案 1 :(得分:3)

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;

尝试通过bitset

编辑(添加代码)

#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, " "));
}

答案 2 :(得分:0)

for (size_t i=0; i<N_SHORTS_IN_BUFFER; i++)
    // perform bitwise ops

其中N_SHORTS_IN_BUFFERmemory中的短片数。

short中的位数为CHAR_BIT * sizeof(short)

答案 3 :(得分:0)

如果您假设unsigned short有16位,那么您可以使用按位运算检索每个位:

for( unsigned short* iter = ms; iter != ms + num_of_ushorts; ++iter )
{
    int bitN = ( *iter ) & ( 1 << N ); // get the N bit
}

答案 4 :(得分:0)

由于_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;