c++ - 如何在C++中以大端方式移动位

标签 c++ endianness

这是小端位移的代码,我想把它转换成大端位移。 请帮帮我。实际上这是使用小端移位的 LZW 解压缩代码。 但我想要大端代码

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;
}
}

最佳答案

你可能想要类似的东西。

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; 

如果您使用的是小字节序,则反转索引,一切都保持不变。

很好rant on endianness以及人们似乎编写的代码,如果您想要更多的话。

关于c++ - 如何在C++中以大端方式移动位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20166738/

相关文章:

c++ - 如何通过对 2 位或更多位数字使用 XOR 运算符来解决此 C++ 问题

c++ - double 随机数数组

java - 如何将字节数组转换为 Int 数组

c - 位字节顺序如何影响 C 中的位移位和文件 IO?

linux - x86 程序集,没有遵循小字节序(或者是?)(Linux)

c++ - 轻量级 http 服务器 C++

java - JNI -> 如何包装 c++ void*

c++ - C++中初始化列表的顺序

c# - 如果 BIGENDIAN 在编译时未解析,为什么它是一个指令?

endianness - 有符号整数的字节序转换