0

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 points the part of my screenshot which are represented by red box. (I mean first member is "00000000" shown in green box). If this is required information, my file is written and shown using by little endian.

With this function I want to append bit at bitset position into my result string

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. Is there anyone to help me ?

newbornToCS
  • 3
  • 1
  • 4
  • It's not 23th, it's 16th bit. Inside a byte, you enumerate bits from right to left (0th is rightmost bit, 7th is leftmost). – nullptr Jul 05 '14 at 15:58
  • @Inspired how it could be ? I've counted it again and I guess 23 ? Could you explain it ? – newbornToCS Jul 05 '14 at 16:00

1 Answers1

0

The first '1' is not the 23th, it's the 16th bit. Well, it might look as a 23-th if you just count from left to right. 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).

So, bit numbers as seen by your function are:

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

nullptr
  • 11,008
  • 1
  • 23
  • 18
  • one more question, How could I print the bits which are pointed by data , I want to do it to check whether my data points the right block or not. – newbornToCS Jul 05 '14 at 16:05
  • because altough I've changed my bitset to 16 manually it did not give 1 – newbornToCS Jul 05 '14 at 16:06
  • I'm not aware of any ready-to-use binary printer. It's easy to implement though. E.g. it's implemented in the first answer to http://stackoverflow.com/questions/111928/is-there-a-printf-converter-to-print-in-binary-format – nullptr Jul 05 '14 at 16:07
  • I'm really so greathful , thanks to you I've found my error and solved it. Thanks again! – newbornToCS Jul 05 '14 at 16:22