反转c中的字节顺序

2 c memory byte bit-manipulation

我在 cs:app datalab 中解决“reverseBytes”时遇到问题。

我必须编写返回相反字节顺序的代码。

示例:输入=0x123456,返回=0x563412

当我使用我的代码时,它不能得分..

int reverseBytes(int x) {
  int mask=0xff;
  int byte1=x>>24;
  int byte2=(x>>16)&mask;
  int byte3=(x>>8)&mask;
  int byte4=x&mask;
  int result=(byte4<<24)|(byte3<<16)|(byte2<<8)|(byte1);

  return result;
}
Run Code Online (Sandbox Code Playgroud)

但是,当我使用其他人的代码时,它需要得分。

int reverseBytes(int x) {
  int t2=~(0xff<<24);
  int s1=(0xff<<16)+0xff;
  int s2=0xff<<8;
  int s3=(s2<<16)+s2;
  int temp=(x&s1)<<8|((x&s3)>>8&t2);
  int q1=(0xff<<8)+0xff;
  int q2=q1<<16;
  int temp2=(temp&q1)<<16|((temp&q2)>>16&(~q2));

  return temp2;
}
Run Code Online (Sandbox Code Playgroud)

我不知道为什么我的代码不能工作..我测试了我的代码和其他人的代码。但我找不到我的代码的结果和另一个代码的结果之间的差异。请帮我..

4pi*_*ie0 5

简单的右移即可获取所需的字节:

#include <stdio.h>
#include <stdint.h>

uint32_t reverse_bytes(uint32_t bytes)
{
    uint32_t aux = 0;
    uint8_t byte;
    int i;

    for(i = 0; i < 32; i+=8)
    {
        byte = (bytes >> i) & 0xff;
        aux |= byte << (32 - 8 - i);
    }
    return aux;
}
Run Code Online (Sandbox Code Playgroud)

测试

int main(void) {
    uint32_t input = 0x123456;
    printf("input: 0x%08x\n", input);
    input = reverse_bytes(input);
    printf("input: 0x%08x\n", input);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

印刷:

输入:0x00123456

输入:0x56341200