[英]How to split binary number into 6-bits binary numbers and add other bits in C?
我正在嘗試將二進制文件(例如0100 0101 0100 0001
)拆分為 6 位大小的二進制文件(獲取0100
、 010101
、 000001
、),並向它們添加兩個二進制文件(將10
添加到000001
=> 10000001
)。
如何在 C 中執行此操作?
您可以使用位掩碼和位移位的組合來提取源的一部分,並在提取后修改值。
要從源中隔離最低有效(“最低”)6 位,請使用按位與( &
)運算符將其屏蔽為二進制 00111111(十六進制 3F); 要將所需的“10”位添加為最高有效(“最高”)2 位,使用按位(含)或( |
)運算符用二進制 10000000(十六進制 80)進行掩碼。
對於無符號源 integer,您可以按順序執行上述操作,每次提取后右移 6 位(使用>>
或>>=
運算符),直到提取所有所需字段。
將源作為unsigned short
並將所需的目標作為 3 個unsigned char
的數組,以下說明了該過程:
#include <stdio.h>
void splitbyte(unsigned short src, unsigned char dst[3])
{
for (int i = 0; i < 3; ++i) {
dst[i] = (src & 0x3F) | 0x80; // Extract the low 6 bits and mask in the top "10! bits
src >>= 6; // Shift right by 6, so next loop extracts next field
}
}
int main(void)
{
unsigned short src = 0x4541; // 0100 0101 0100 0001
unsigned char dst[3];
splitbyte(src, dst);
// You could printf in a loop but I wanted to comment each value ...
printf("%02X\n", (unsigned)(dst[0])); // 81 = 10 000001
printf("%02X\n", (unsigned)(dst[1])); // 95 = 10 010101
printf("%02X\n", (unsigned)(dst[2])); // 84 = 10 000100
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.