c - 字每2位为符号

标签 c

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

我需要帮助才能将其更改为每 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/

相关文章:

c - 指向 long 的空指针

c - 在 linux 内核模式下使用 vfs_link

c - “inline __attribute__((always_inline))” 在函数中是什么意思?

c - 如何在结构体中初始化结构体数组?

c - 为什么我会出现段错误?

C套接字编程——printf不在屏幕上打印任何东西

c - 将数据存储在程序中而不是外部文件中

c - 通过索引访问字符串与前进指针

c - 为什么数据类型是自对齐的?

c - 编译 ipsec 工具时出错...PATH_IPSEC_H 实际上是什么意思?