c - 给字节现有的字节值(作业)

标签 c bit-manipulation

我需要在切换某个 int 的值时进行赋值。例如:0xaabbccdd应该变成0xddccbbaa

我已经从给定数字中提取了所有字节,并且它们的值是正确的。

unsigned int input;

scanf("%i", &input);

unsigned int first_byte = (input >> (8*0)) & 0xff;
unsigned int second_byte = (input >> (8*1)) & 0xff;
unsigned int third_byte = (input >> (8*2)) & 0xff;
unsigned int fourth_byte = (input >> (8*3)) & 0xff;

现在我试图将一个空的 int 变量(又名 00000000 00000000 00000000 00000000)设置为那些字节值,但转过身来。那么我怎么能说空变量的第一个字节是给定输入的第四个字节呢?我一直在尝试按位运算的不同组合,但我似乎无法理解它。我很确定我应该能够做类似的事情:

answer *first byte* | fourth_byte;

我将不胜感激任何帮助,因为我已经被卡住了几个小时并一直在寻找答案。

最佳答案

基于您的代码:

#include <stdio.h>

int main(void)
{
    unsigned int input = 0xaabbccdd;
    unsigned int first_byte = (input >> (8*0)) & 0xff;
    unsigned int second_byte = (input >> (8*1)) & 0xff;
    unsigned int third_byte = (input >> (8*2)) & 0xff;
    unsigned int fourth_byte = (input >> (8*3)) & 0xff;

    printf(" 1st : %x\n 2nd : %x\n 3rd : %x\n 4th : %x\n", 
        first_byte, 
        second_byte, 
        third_byte, 
        fourth_byte);

    unsigned int combo = first_byte<<8 | second_byte;
    combo = combo << 8 | third_byte;
    combo = combo << 8 | fourth_byte;

    printf(" combo : %x ", combo);

    return 0;
}

它将输出0xddccbbaa

这里有一个更优雅的函数来做到这一点:

unsigned int setByte(unsigned int input, unsigned char byte, unsigned int position)
{
    if(position > sizeof(unsigned int) - 1)
        return input;

    unsigned int orbyte = byte;
    input |= byte<<(position * 8);

    return input;
}

用法:

unsigned int combo = 0;
    combo = setByte(combo, first_byte, 3);
    combo = setByte(combo, second_byte, 2);
    combo = setByte(combo, third_byte, 1);
    combo = setByte(combo, fourth_byte, 0);

    printf(" combo : %x ", combo);

关于c - 给字节现有的字节值(作业),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22530956/

相关文章:

c++ - Boost 与成员函数的绑定(bind)导致编译错误

c - GDB 影响 setcontext 结果

c - 为什么这个简单的文件读取程序第一次运行需要 30 秒才能执行?

c - 生产者、消费者 POSIX

javascript - 我的按位逻辑有什么缺陷?

c - 将两个溢出的整数乘以三分之一

java - 管理大量 boolean 状态的最有效方法

c - 在单独的线程中使用全局变量控制 while 循环

c# - 计算 X 位掩码的最快方法?

C/C++ 中的编译时位运算