Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In a byte, how to swap the 4 higher bits with its 4 lower bits

Tags:

c

byte

I had an interview yesterday.

One of the question i've been asked was: how can one replace the 4 higher bits of a byte with its 4 lower bits. We're talking on native C here, btw.

For example, consider the following byte: AB The output should be: BA

Well, the guy there told me it can be done within a single command. I've only managed to do it in 3 commands.

I asked him for the answer, but he was reluctant.

Thanks!

like image 238
Amir Avatar asked May 22 '13 19:05

Amir


2 Answers

uint8_t b = 0xab;

b = (b << 4) | (b >> 4);

b now equals 0xba.

Is that what you meant?

like image 192
Omri Barel Avatar answered Sep 30 '22 17:09

Omri Barel


I think this might be the answer your interviewer was looking for:

unsigned char a = 0xab;
a *= 16.0625;

It's short and pretty, but it won't be too efficient when compiled.

like image 32
Paul Hankin Avatar answered Sep 30 '22 15:09

Paul Hankin