【发布时间】:2021-01-06 01:55:43
【问题描述】:
提取和修改位
从打包的 final_value 中的一个位置选择 n 个位并写入任意位置,而不修改 uint16_t test_bit = 0x3048 的原始内容。
预期输出 = 0x5048
例如: 从 final_val 中选取 010(3bits from position 17) 并写入任意位置(位置 11 )
0x3048 = 0111 0000 0100 1000;
0x5048 = 0101 0000 0100 1000
几个例子:
例子 A:
粗体是提取的。我们从 Val_1 中提取位 0 到 7,并仅替换 Val_2 中的位 0 到 7,使位 8 到 15 保持不变。
Val_1 0x1b7 0000 0001 1011 0111
Val_2 0x27b7 0010 0111 1011 0111
示例 B:
从 Val1[从位 8 到 10] 中提取 3 位,并将其替换为 Val_2[从 11 到 13]。
Val_1 0x129 0000 0001 0010 1001
Val_2 0x4C48 0100 1100 0100 1000
到目前为止尝试过:
#include <stdio.h>
#include <stdint.h>
void read_and_write(uint32_t* final_val, uint16_t* write_val, uint8_t start_pos, uint8_t end_pos)
{
uint32_t temp = *final_val;
*write_val = (uint16_t) ((temp >> start_pos) & ((1 << end_pos) - 1)); // store the desired number of bits in write_val
*final_val = (temp >> end_pos); //shift final_val by end_pos since those bits are already written
printf("\n temp %x, write_val %x, final_val %x ", temp, *write_val, *final_val);
}
void main()
{
uint32_t final_val = 0x0; //Stores 20 extracted bits from val1, val2 and val3 into final_val (LSB to MSB in order)
uint16_t ext_val1 = 0x80;
uint8_t ext_val2 = 0x0;
uint8_t ext_val3 = 0x2;
final_val = (ext_val1 | (ext_val2 << 9) | (ext_val3 << 17));
printf ("\n final_val %x", final_val);
uint16_t data_1, data_2, data_3, write_val1, write_val2, write_val3;
// Read first 9 bits of final_val and write only into [0:9] position of existing data_1
uint8_t start_pos = 0;
uint8_t end_pos = 9;
data_1 = 0x80;
read_and_write(&final_val, &write_val1, start_pos, end_pos);
write_val1 = write_val1 | data_1;
// Read next 8 bits of final_val and write only into [0:8] position of existing data_2
start_pos = 0;
end_pos = 8;
data_2 = 0x27b7;
read_and_write(&final_val, &write_val2, start_pos, end_pos);
write_val2 = write_val2 | data_2;
//Read next 3 bits of final_val and write only into[13:11] position of existing data_3
start_pos = 11;
end_pos = 13;
data_3 = 0x3048;
read_and_write(&final_val, &write_val3, start_pos, end_pos);
write_val3 = write_val3 | data_3;
printf ("\n val1 0x%x val2 0x%x val3 0x%x final_val 0x%x", write_val1, write_val2, ext_val3, final_val);
}
有人可以帮忙吗?使用旧方法忽略陈旧的代码。
【问题讨论】:
-
到目前为止你做了什么?
-
@P__J__ 更新了我上面的代码。
-
非有效位总是保证为
0?也许您需要将它们过滤掉:(ext_val1 & 0x1ff)、(ext_val2 & 0xff)、(ext_val3 & 0x7) -
示例中的位数不一致:示例A中的16位值中没有位置17,示例B中的3位是从位置8到10提取的,而不是从5到7.
标签: c bit-manipulation operators bitwise-operators bit