【问题标题】:How to Modify a specific Byte in an Interger如何修改整数中的特定字节
【发布时间】:2016-01-20 23:00:30
【问题描述】:

我有以下代码-

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

  • 案例一:

    输入: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

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

【问题讨论】:

  • 转换为 char* 并使用下标运算符。不过请注意字节顺序。
  • @cad 一个更干净、更便携的解决方案是 bitshift/mask。
  • @EugeneSh。是的,很好。

标签: c algorithm bit-manipulation


【解决方案1】:

只需使用无符号位移。

#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

【讨论】:

    【解决方案2】:
    int a;
    ((char*)&a)[0]=0x54
    ((char*)&a)[1]=0x21
    ((char*)&a)[2]=0xFB
    ((char*)&a)[3]=0x32
    

    最好使用按位移位,但是这个好用好记。

    【讨论】:

    • 这在大小端系统上会有不同的结果。
    • 好吧,我不太确定,@Barmar 你认为是吗?
    • 它将是 0x5421FB32 在大端和 0x32FB2154 在小端,但由于严格的别名规则,在此之后直接通过 a 访问值也是未定义的行为。您还忘记了行尾的;
    猜你喜欢
    • 2019-09-15
    • 2018-11-13
    • 2020-01-20
    • 1970-01-01
    • 2017-10-15
    • 1970-01-01
    • 2021-02-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多