如何修改整数中的特定字节

时间:2015-10-21 19:45:30

标签: c algorithm bit-manipulation

我有以下代码 -

int main ()
{
    unsigned int    u4Val       = 0xAABBCCDD;
    unsigned char   u1User_Val  = 0x00;

    int Byte_Location = 0;

    printf ("\n %08X \n", val);

    printf ("\n Enter Byte Location : ");
    scanf  ("%d", &Byte_Location);  /* Get - 0 or 1 or 2 or 3 */

    printf ("\n Enter Value to Write : ");
    scanf ("%02X", &u1User_Val);

    /*====== Code to Write on the Byte Location in u4Val ======*/

    printf ("\n %08X \n", u4Val);

    return 0;
}

示例IO

  • 案例1:

    输入:Byte_Location = 0和Value = 0x54

    输出:0x54BBCCDD

  • 案例2:

    输入:Byte_Location = 1和Value = 0x21

    输出:0xAA21CCDD

  • 案例3:

    输入:Byte_Location = 2和Value = 0xFB

    输出:0xAABBFBDD

  • 案例4:

    输入:Byte_Location = 3和Value = 0x32

    输出:0xAABBCC32

请帮我编写待处理部分的代码。提前谢谢。

2 个答案:

答案 0 :(得分:0)

只需使用无符号位移。

#include <assert.h>
#include <limits.h>
#include <stdio.h>

unsigned ByteReplace(unsigned x, unsigned byte_index, unsigned char byte_new) {
  assert(sizeof x * CHAR_BIT >= 4 * 8);
  printf("Input: Byte_Location = %u and Value = 0x%02X\n", byte_index,
          byte_new);

  // Typically I'd expect byte_index to imply the least significant byte.  OP has otherwise
  byte_index = 3 - byte_index;

  unsigned mask = 0xFFu << byte_index * 8;
  unsigned y = (~mask & x) | (byte_new << byte_index * 8);
  printf("Output: 0x%08X\n", y);
  return y;
}

int main(void) {
  unsigned int u4Val = 0xAABBCCDD;
  ByteReplace(u4Val, 0, 0x54);
  ByteReplace(u4Val, 1, 0x21);
  ByteReplace(u4Val, 2, 0xFB);
  ByteReplace(u4Val, 3, 0x32);
  return 0;
}

输出

Input: Byte_Location = 0 and Value = 0x54
Output: 0x54BBCCDD
Input: Byte_Location = 1 and Value = 0x21
Output: 0xAA21CCDD
Input: Byte_Location = 2 and Value = 0xFB
Output: 0xAABBFBDD
Input: Byte_Location = 3 and Value = 0x32
Output: 0xAABBCC32

答案 1 :(得分:-1)

int a;
((char*)&a)[0]=0x54
((char*)&a)[1]=0x21
((char*)&a)[2]=0xFB
((char*)&a)[3]=0x32

最好使用按位移位,但这个易于使用并且记住。