Amir
Amir

Reputation: 171

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

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!

Upvotes: 5

Views: 5111

Answers (5)

Paul Hankin
Paul Hankin

Reputation: 58221

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.

Upvotes: 8

Joachim Isaksson
Joachim Isaksson

Reputation: 180917

In gcc on x86, you can use ror as a single inline assembler operation;

unsigned char a = 0x45;

asm("ror $4,%1" : "+r" (a));

printf("0x%x\n", a);

Outputs 0x54.

As an alternative, as suggested by OmriBarel in the comments, if you can do some preparations, a lookup will work also;

uint8_t* lookup = malloc(256);
unsigned int i;
for(i=0; i<256; i++) lookup[i]= i>>4 | i<<4;

uint8_t a = 0x54;
a = lookup[a];
printf("0x%x\n", a);

Outputs 0x45.

Upvotes: 6

AnT stands with Russia
AnT stands with Russia

Reputation: 320421

The question is not really meaningfully worded. What's "one command"? What's "command"?

One can do that by using a translation table, for example. The actual swap will look like b = table[b], assuming the table was initialized in advance. Is that one "command" or not? Does the assignment operator count as a separate "command" in addition to [] operator?

Upvotes: 2

John
John

Reputation: 7339

Perhaps I'm just catching on a technicality here, but the instruction you've given us is not to swap the two nibbles, but just replace the higher one with the lower one. In my mind that would convert 0xAB into 0xBB, not necessarily 0xBA.

b = (b << 4) | (b & 0xf);

does that. If you're not worried about what happens to the lower bits, then I would just

b <<= 4;

Upvotes: 1

Omri Barel
Omri Barel

Reputation: 9480

uint8_t b = 0xab;

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

b now equals 0xba.

Is that what you meant?

Upvotes: 10

Related Questions