Reputation: 89
I have just started c-programming and I have a problem to replace the least significant bit (LSB) with the most significant bit (MSB).
For example, the first key (key is 32 bit) is 11110000, and after the transformation, it would be 11100001, and then 11000011, and then 10000111, 00001111, 00011110 and so on.
Here is my code that I have tried:
for (int i = 0; i < 5; i++)
{
uint32_t a = (1 << 31) & key;
key = (key << 1);
key &= ~(1 << 1);
key |= (a << 1);
}
Upvotes: 0
Views: 4687
Reputation: 2304
Assuming key
is also of type uint32_t
, you can try this
for (int i = 0; i < 5; i++)
{
uint32_t a = key >> 31; //convert MSB to LSB
key <<= 1; // shift key 1 bit to the left, (discarding current MSB) making space for new LSB
key |= a; // append LSB
}
Upvotes: 1
Reputation: 3413
Looks like you already accepted an answer, but I'm gonna give you a little more feedback to hopefully help you on your way. You've got a couple problems:
First, your example key 11110000 is confusing. Is that binary or hex? Binary 0b11110000 is an 8-bit number, not a 32-bit number. Whereas hexadecimal 0x11110000 is a 32-bit number but it probably isn't going to bitwise-shift as you might expect. For example, 0x11110000 shifted left 1 bit becomes 0x22220000, not 0x11100001.
Second, I see what you're trying to do by saving the MSb and trying to bitwise-OR it in later as the LSb. But your shift amounts are wrong. You want to bitwise-OR the value into bit 0, not bit 1. So your shift amount would be << 0, not << 1. Since << 0 is essentially a no-op you can just leave it off.
Here are some minor changes to your code that should make things right. I've added comments to hopefully describe what I changed.
for (int i = 0; i < 5; i++)
{
//uint32_t a = (1 << 31) & key;
// This shifts key 31 bits to the right, with the result being
// bit31 becomes bit0. Since you are using an unsigned int,
// all the upper bits will be 0.
uint32_t bit0 = key >> 31;
key = (key << 1);
// This step is unnecessary and also incorrect. I believe you
// are trying to zero out bit0. The bitwise shift left (above) will have
// shifted in a zero already.
//key &= ~(1 << 1);
// Now bitwise-OR in bit0.
//key |= (a << 1);
key |= bit0;
}
Upvotes: 1