简体   繁体   English

如何在C ++中的Big Endian中移位位

[英]How to shift bits in big endian in c++

Here is code for little endian bit shift, i want to convert it in big endian bit shift. 这是小端字节移的代码,我想将其转换成大端字节移。 please help me out. 请帮帮我。 actually this is LZW decompression code using little endian shift. 实际上,这是使用小尾数移位的LZW减压代码。 but i want big endian code 但我想要大端序代码

unsigned int input_code(FILE *input)
{
unsigned int val;
static int bitcount=0;
static unsigned long inbitbuf=0L;

  while (bitcount <= 24)
  {
      inbitbuf |=(unsigned long) getc(input) << (24-bitcount);
      bitcount += 8;
  }

  val=inbitbuf >> (32-BITS);
  inbitbuf <<= BITS;
  bitcount -= BITS;

  return(val);
}


void output_code(FILE *output,unsigned int code)
{
static int output_bit_count=0;
static unsigned long output_bit_buffer=0L;

output_bit_buffer |= (unsigned long) code << (32-BITS-output_bit_count);
output_bit_count += BITS;
while (output_bit_count >= 8)
{
    putc(output_bit_buffer >> 24,output);
    output_bit_buffer <<= 8;
    output_bit_count -= 8;
}
}

You probably want something like. 您可能想要类似的东西。

unsigned char raw[4];
unsigned int val;
if (4 != fread(raw, 1, 4, input)) {
  // error condition, return early or throw or something
}
val = static_cast<unsigned int>(data[3])
    | static_cast<unsigned int>(data[2]) << 8 
    | static_cast<unsigned int>(data[1]) << 16 
    | static_cast<unsigned int>(data[0]) << 24; 

if you were doing little endian, reverse the indexes and everything stays the same. 如果您在进行小端排序,则反转索引,一切都保持不变。

A good rant on endianness and the code that people seem to write, if you want more. 如果需要更多内容,则对字节序和人们似乎在编写的代码要好一点。

Its a good idea to mask (perform a bitwise OR against) the bytes one at a time before shifting them . 在移动字节之前,一次屏蔽一个字节(对它执行按位“或”操作)是一个好主意。 Obviously if you are shifting a 16 bit integer the unmasked bits will just be pushed off either end into oblivion. 显然,如果您要移位16位整数,则未屏蔽的位将仅被推到两端而被遗忘。 But for integers larger that 16 bits (I actually had to use 24 bit integers once) it's best to mask each byte before shifting and recombining (perform a bitwise OR on) them. 但是对于大于16位的整数(我实际上必须使用24位整数一次),最好在移位和重新组合(对它们执行按位“或”运算之前,先屏蔽每个字节)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM