我在解决 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;
}
但是,当我使用别人的代码时,它需要一个分数。
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;
}
我不知道为什么我的代码不能工作.. 我测试了我的代码和其他人的代码。 但我找不到我的代码结果和另一个代码结果之间的区别。 请帮助我..
最佳答案
简单的右移以获得所需的字节就可以了:
#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;
}
Test :
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;
}
打印:
输入:0x00123456
输入:0x56341200
关于c - c中的字节顺序反转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32786493/