gpt4 book ai didi

c - 字每2位为符号

转载 作者:太空宇宙 更新时间:2023-11-04 06:10:48 26 4
gpt4 key购买 nike

我有一个函数可以一点一点地读取一个单词并更改为符号:

我需要帮助才能将其更改为每 2 位读取一次并更改为符号。我对此一无所知,我需要你们的帮助

void PrintWeirdBits(word w , char* buf){
word mask = 1<<(BITS_IN_WORD-1);
int i;
for(i=0;i<BITS_IN_WORD;i++){
if(mask & w)
buf[i]='/';
else
buf[i]='.';
mask>>=1;
}
buf[i] = '\0';
}

需要的符号:

00 - *
01 - #
10 - %
11 - !

最佳答案

这是我对您的问题的建议。使用查找表进行符号解码将消除 if 语句中的需要。

(我假设 word 是一个无符号的 16 位数据类型)

#define BITS_PER_SIGN 2
#define BITS_PER_SIGN_MSK 3 // decimal 3 is 0b11 in binary --> two bits set
// General define could be:
// ((1u << BITS_PER_SIGN) - 1)
#define INIT_MASK (BITS_PER_SIGN_MSK << (BITS_IN_WORD - BITS_PER_SIGN))

void PrintWeirdBits(word w , char* buf)
{
static const char signs[] = {'*', '#', '%', '!'};
unsigned mask = INIT_MASK;
int i;
int sign_idx;

for(i=0; i < BITS_IN_WORD / BITS_PER_SIGN; i++)
{
// the bits of the sign represent the index in the signs array
// just need to align these bits to start from bit 0
sign_idx = (w & mask) >> (BITS_IN_WORD - (i + 1)*BITS_PER_SIGN);
// store the decoded sign in the buffer
buf[i] = signs[sign_idx];
// update the mask for the next symbol
mask >>= BITS_PER_SIGN;
}

buf[i] = '\0';
}

Here它似乎在工作。只要不费吹灰之力,它就可以更新为符号的任何位宽的通用代码,只要它是 2 的幂(1、2、4、8)并且小于 BITS_IN_WORD

关于c - 字每2位为符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57247451/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com