简体   繁体   English

从位序列中提取一位C ++

[英]Extracting a bit from the sequence of bits c++

Hi everyone I have the following function : 大家好,我有以下功能:

#define GET_BIT(p, n) ((((unsigned char *)p)[n/8] >> (n%8)) & 0x01)

void extractBit(void const * data, int bitIndex)
{
    string  result = "";
        result.append(std::to_string(GET_BIT(data, bitIndex)));      
}

and following link shows my bits which are pointed by void const* data pointer : http://prntscr.com/3znmpz . 下面的链接显示了我的位,这些位由void const* data指针指向: http : //prntscr.com/3znmpz void const* data points the part of my screenshot which are represented by red box. void const* data指向我的屏幕截图中用红色框表示的部分。 (I mean first member is "00000000" shown in green box). (我的意思是第一个成员是绿色框中显示的“ 00000000”)。 If this is required information, my file is written and shown using by little endian. 如果这是必需的信息,则使用little endian写入并显示我的文件。

With this function I want to append bit at bitset position into my result string 有了这个功能,我想追加在bitset的位置位进入我的结果字符串

For example, when extractBit(data,23) I want to add first 1 in the red box into my result string but it gives me 0. Altough I've looked at my code through a couple hours, I could not find my mistake. 例如,当extractBit(data,23)我想将红色框中的第一个1添加到我的结果字符串中,但它给我0。尽管我已经看了几个小时的代码,但我找不到我的错误。 Is there anyone to help me ? 有没有人可以帮助我?

The first '1' is not the 23th, it's the 16th bit. 第一个“ 1”不是第23位,而是第16位。 Well, it might look as a 23-th if you just count from left to right. 好吧,如果只是从左到右计数,它可能看起来像是第23位。 But that's not how your function works. 但这不是您的函数的工作方式。

Inside a byte, you enumerate bits from right to left (0th is rightmost bit, 7th is leftmost, which is a common convention and should be fine). 在一个字节内,您从右到左枚举位(第0位是最右边的位,第7位是最左边的,这是常规约定,应该没问题)。

So, bit numbers as seen by your function are: 因此,您的函数看到的位数是:

7 6 5 4 3 2 1 0 | 7 6 5 4 3 2 1 0 | 15 14 13 12 11 10 9 8 | 15 14 13 12 11 10 9 8 | 23 22 21 20 19 18 17 16 | 23 22 21 20 19 18 17 16 | 31 30 ... 31 30 ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM