字节交换和填充留在空间中,在C中为0

时间:2017-10-03 04:09:15

标签: c byte padding swap

我的程序应该将第n个字节切换到第m个位置,这是我到目前为止所做的:

        unsigned int x = 12456812; 
        int xn = x;
        int xm = x;

          int mask = 0;
          int mask_m = 0xFF << (m << 3) ;
          int mask_n = 0xFF << (n << 3);

        xn = x >> (n << 3);
        xn = xn & 0xFF;

        xm = x >> (m << 3) ;
        xm = xm & 0xFF;




        mask = (mask_m | mask_n)  ^ 0xFFFFFFFF;

        int x_swapped = (x & mask) | (xm << (n <<3)) | (xn << (m <<3));

        printf("switch: %d\n", x_swapped);

我的程序返回1293932,它非常接近预期的结果,但它需要在第一个字节后填充0。 (见例)

Original base10 number:
    12456812 (          1011 1110 0001 0011 0110 1100) 

Program returns: 
    1293932  (0001 0111 1011 1110            0110 1100) 
(space intentionally left blank, for demonstration purposes) 


Byte swapped number (objective): 
   331219052 (0001 0111 1011 1110 0000 0000 0110 1100)  

正如您在示例中所看到的,移位不是填充0,而是交换字节。

抱歉英语不好

2 个答案:

答案 0 :(得分:1)

您可以在函数中执行字节交换并返回交换的值。

类似的东西:

#include <stdio.h>

unsigned int swap_byte_n_and_m(unsigned int x, unsigned int n, unsigned int m)
{
                                            // Example x=0x00be136c, n=3, m=1
  unsigned int mask_n = 0xFF << (n << 3);   // mask_n = 0xff000000
  unsigned int mask_m = 0xFF << (m << 3);   // mask_m = 0x0000ff00
  unsigned int data_n = x & mask_n;         // data_n = 0x00000000
  unsigned int data_m = x & mask_m;         // data_m = 0x00001300
  x = x & ~mask_n & ~mask_m;                // x      = 0x00be006c
  if (n>m)
  {
    data_n = data_n >> ((n-m) << 3);        // data_n = 0x00000000
    data_m = data_m << ((n-m) << 3);        // data_m = 0x13000000
  }
  else
  {
    data_n = data_n << ((m-n) << 3);
    data_m = data_m >> ((m-n) << 3);
  }
  x = x | data_n | data_m;                  // x      = 0x13be006c
  return x;
}

int main(void)
{
  unsigned int x = 12456812;
  printf("Before swap : %12u - 0x%08x\n", x, x);
  x = swap_byte_n_and_m(x, 3, 1);
  printf("After swap  : %12u - 0x%08x\n", x, x);
  return 0;
}

输出:

Before swap :     12456812 - 0x00be136c
After swap  :    331219052 - 0x13be006c

答案 1 :(得分:0)

另一种方式:

// n and m should be between 0 and 3
unsigned int swap_byte_to_from(unsigned int x, unsigned int n, unsigned int m)
{
    unsigned char tmp[4];

    memcpy(tmp, &x, sizeof(int));
    x = 0;
    int i = 4;
    while (i--)
        x |= ((i == n) ? tmp[m] : (i == m) ? tmp[n] : tmp[i]) << (i << 3);
    return x;
}