我有以下代码-
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且值= 0x54
输出:0x54BBCCDD
情况2:
输入:Byte_Location = 1且值= 0x21
输出:0xAA21CCDD
情况3:
输入:Byte_Location = 2且值= 0xFB
输出:0xAABBFBDD
情况4:
输入:Byte_Location = 3,值= 0x32
输出:0xAABBCC32
请帮助我在待处理部分编码。提前致谢。
最佳答案
只需使用无符号移位。
#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
关于c - 如何修改整数中的特定字节,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33267926/