如何将num1的第一个字节与C中的num2的最后一个字节交换?

时间:2015-12-25 15:57:31

标签: c

我正在用num1的最后一个字节交换num2的第一个字节,我试过但通过((num1>>8*n)&0xff)获得了32位int的特定字节。

3 个答案:

答案 0 :(得分:2)

尝试这样做

long num1 = 0x000000ff;
long num2 = 0xcc000000;

long temp = num1;
num1 = (((unsigned long)num1) & 0xffffff00) | ((((unsigned long)num2) >> 24) & 0x000000ff);
num2 = (((unsigned long)num2) & 0x00ffffff) | ((((unsigned long)temp) << 24) & 0xff000000);     

printf ("num1 : %#010lX\n", num1);
printf ("num2 : %#010lX\n", num2);

使用掩码时,我们将覆盖32位值的所需部分并消除有符号值的负面影响,而不是按位OR的值的连续部分。

结果:

enter image description here

答案 1 :(得分:1)

要将num1的第一个字节与num2的最后一个字节交换,请使用以下代码:

unsigned long low = (num1 & 0x000000ff) << 24;
unsigned long high = num2 >> 24;
num1 = (num1 & 0xffffff00) | high;
num2 = (num2 & 0x00ffffff) | low;

假设x输入数字为unsigned long。使用此代码交换相同数字的第一个和最后一个字节:

unsigned long high = (x >> 24);
unsigned long low = (x & 0x000000ff) << 24;
unsigned long temp = (x & 0x00ffff00);
unsigned long output = (temp | high | low);

答案 2 :(得分:1)

我发现union很容易处理这种字节操作:

typedef union myUnion
{
    int i;
    unsigned char bytes[4];
};

...
void swap(unsigned char *l, unsigned char *r)
{
    unsigned char temp = *l;
    *l = *r;
    *r = *l;
}

...

union myUnion u_a, u_b;
u_a.i = ...;
u_b.i = ...;
swap(&u_a.bytes[0], &u_b.bytes[3]);