int from 0 to 8, to binary ("progress bar")

Hello :slight_smile:

It's been a long time since the last time I wrote code for arduino, I'm rusted :slight_smile:

Ok so here is the problem, I want to transform a number from 0 to 8, to a binary number, such as:

0 -> 0b00000000 = 0
1 -> 0b10000000 = 128
2 -> 0b11000000 = 192
3 -> 0b11100000 = 224
4 -> 0b11110000 = 240
5 -> 0b11111000 = 248
6 -> 0b11111100 = 252
7 -> 0b11111110 = 254
8 -> 0b11111111 = 255

The answer should be obvious and easy, but I can't remember :S

Help please? Thanks in advance :slight_smile:

Edit: Pff I know that was easy, I just found it seconds after posting this topic:
256 - (1 << (8-count))(where count is my number from 0 to 8 )

Sorry... Maybe this will help someone else :slight_smile:

I want to transform a number from 0 to 8, to a binary number

The Arduino stores numbers in binary. No transformation is needed. Job done.

You can use bit shifting.

int a = 0; // binary: 00000000
int b = a | 128; // binary: 10000000
b >> 1; // binary: 01000000 // I split this
int c = b | 128 // binary: 11000000 // and this, to show what is happening

This is probably not the best way to do it, but I dont know for sure. I can't test it on my end.

2n-1 is a simpler way, if you don't mind the bit reversal.