Swapping bits for little endian to big endian

Long story made very very short. I need to swapping bit of a byte from little endian to big endian.

What is the easiest way? Is there a function?

something like this you mean?

uint8_t bit_endian_swap=0, data = 123;

for(unit8_t i=0; i<7;++i){
   bit_endian_swap = (bit_endian_swap|(data>>i)&0x01))<<1; 
}

return bit_endian_swap|(data>>7)&0x01);

sherzaad:
something like this you mean?

uint8_t bit_endian_swap=0, data = 123;

for(unit8_t i=0; i<7;++i){
  bit_endian_swap = (bit_endian_swap|(data>>i)&0x01))<<1;
}

return bit_endian_swap|(data>>7)&0x01);

Yes. If you are doing much of this, you might want to use this function to calculate a table once and for all.

unsigned char reverse[256] = {0x0, 0x80, 0x40 and so forth
.
.
DON'T scratch them out by hand, write a program to use the above function to precisely and neatly make this whole table paerfect, then paste in into your code.
.
.
0x7f, 0xff};

reversing becomes array reference boom.

littleEndian = revers[bigEndian];

a7

alto777:
Yes. If you are doing much of this, you might want to use this function to calculate a table once and for all.

unsigned char reverse[256] = {0x0, 0x80, 0x40 and so forth
.
.
DON'T scratch them out by hand, write a program to use the above function to precisely and neatly make this whole table paerfect, then paste in into your code.
.
.
0x7f, 0xff};

reversing becomes array reference boom.

littleEndian = revers[bigEndian];

a7

That would be the speed versus (RAM) memory trade off comes into play.

adwsystems:
That would be the speed versus (RAM) memory trade off comes into play.

you could always use "PROGMEM" to store the table! :slight_smile:

sherzaad:
you could always use "PROGMEM" to store the table! :slight_smile:

Maybe, but that's getting pretty full too. :confused:

Sketch uses 21938 bytes (68%) of program storage space. Maximum is 32256 bytes.
Global variables use 1724 bytes (84%) of dynamic memory, leaving 324 bytes for local variables. Maximum is 2048 bytes.

Geez, you ain't got room anywhere for a lousy 256 byte table? I'd use a table no matter the time/space, at least on a processor with such huge memory!

And if you are doing the same with longer integers, you can still use the same table or not insane in some circumstances make a large table the same 'xact way.

a7

You may find some inspiration here.

dougp:
You may find some inspiration here.

Nice.

I like the table created by the preprocessor, good stuff. Although I wondered enough to look - the table it produces is one line of code 4906 chars long…

C++ places no limit on line length, ok.

a7