如何把位转换成字符数组 [英] How to put bits into a character Array

查看:113
本文介绍了如何把位转换成字符数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要知道如何把位转换成字符数组。

I need to know how to put bits into a character array.

例如,

我想把0001位转换成使用C或C ++中的字符数组。

I want to put 0001 bits into a character array using C or C++.

需要你的帮助球员。谢谢你。

Need your help guys. Thanks.

推荐答案

这也许更通用的code会给你的理念是:

Maybe this more generic code will give you the idea:

void setBitAt( char* buf, int bufByteSize, int bitPosition, bool value )
{
    if(bitPosition < sizeof(char)*8*bufByteSize)
    {
        int byteOffset= bitPosition/8;
        int bitOffset = bitPosition - byteOffset*8;

        if(value == true)
        {
            buf[byteOffset] |=  (1 << bitOffset);
        }
        else
        {
            buf[byteOffset] &= ~(1 << bitOffset);;
        }
    }
}

//use it as follow:
char chArray[16];
setBitAt(chArray,16*sizeof(char),5,true); //to set bit at pos 5 to 1

这篇关于如何把位转换成字符数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆