I have hard time to understand what this doc tells me: https://www.microchip.com/webdoc/AVRLibcReferenceManual/FAQ_1faq_use_bv.html

I has a macro called _BV that

convert a bit number (usually within a byte register) into a byte value

And the example tells this

_BV(3) => 1 << 3 => 0x08

I am kinda used to bits and bytes etc. But I don't understand what the 3 in this example is? It says it converts a bit number but 3 is not binary it is an integer. And the macro resolves it to 0x08 which is the value of 8 in decimal.

I am very confused. I hope someone can explain to me what is happening here!

  • when you see 0x08, do not think "decimal" ... think "hexadecimal" ..... hexadecimal numbers convert to binary easily ..... for example, 0x98 is same as 0b10011000
    – jsotola
    May 30 '19 at 23:35

The bits within a byte are numbered 0 through 7 from right to left. The rightmost (least significant) is bit 0, next is bit 1... and the leftmost (most significant) is bit 7.

The expression _BV(3) builds a byte where bit 3 is set (is 1) and all other bits are clear (are 0). In binary it looks like this:

position:   7  6  5  4  3  2  1  0
bit value:  0  0  0  0  1  0  0  0

The macro expands to 1<<3, which takes the integer 1 (0b00000001 in binary) and shifts all its bits by three positions to the left. The result can be written 0b00001000 in binary, 0x08 in hexadecimal, and 8 in decimal.

  • and bear in mind @xetra11 that it is only coincidence that in this case, the hexadecimal number and the decimal number are the same. Had bit 4 been set to 1 instead of bit 3, it would have been 0x10 in hexadecimal, and 16 in decimal! It may be useful to consider that decimal numbers are all "base 10" (hence the word DEC-imal). But binary numbers are base '2', and hexadecimal numbers are base 16. The base - 1` is the highest number that can be in a 'digit' before a carry must happen to represent the number. For hexidecimal, in order to have 16 digits, it goes from 0-9 followed by A-F.
    – Randy
    May 31 '19 at 1:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.