Tao Liu
Tao Liu

Reputation: 35

swap a length of bits in 2 bytes

I would like to input 2 unsigned char variables:a and b. If use a(0) for bit 0 in a, I would like to swap a(6) to a(1) with b(6) to b(1). Finally I wish to get 2 new unsigned char_type variables:a1 and b1 with required bits swapped. I would love to know that is there method to address this issue in C language?

An further requirement is that add 2 variables: pa and pb to decide the start position for the length. For example: if pa=6, pb=7, I have to swap a(6) to a(1) with b(7) to b(2).

Any good solution?

Upvotes: 1

Views: 218

Answers (3)

sehe
sehe

Reputation: 392921

Aha. I get it now

unsigned const char mask = 0x3e;

usigned char a,b; // input somehow

unsigned char a2=a, b2=b;

a2 = (a2 & ~mask) | (b & mask);
b2 = (b2 & ~mask) | (a & mask);

Upvotes: 1

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136237

Given integers, e.g.:

uint32_t a = 0xff00ff00;
uint32_t b = 0x00ff00ff;

This is how you swap entire values:

a ^= b;
b ^= a;
a ^= b;

If you want to swap only specific bits, add a mask there:

uint32_t mask = 0x0000ffff; // only swap the lower 16 bits
a ^= (b & mask);
b ^= (a & mask);
a ^= (b & mask);

The above requires 6 bitwise operations, whereas ecatmur's solution requires only 5.

Upvotes: 0

ecatmur
ecatmur

Reputation: 157344

I'd be inclined to use xor masking:

mask = 0x3e;    // 0b00111110
diff = (a & mask) ^ (b & mask);
a1 = a ^ diff;
b1 = b ^ diff;

Upvotes: 3

Related Questions