Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- class BitsExchange
- {
- static void Main()
- {
- //Write a program that exchanges bits 3, 4 and 5 with bits 24, 25 and 26 of given 32-bit unsigned integer.
- //First I read the number from the console
- Console.Write("Please insert an integer: ");
- uint n = uint.Parse(Console.ReadLine());
- //Then I get the neeeded bits 1 by 1 so I can exchange them later
- uint bit3 = n >> 3;
- bit3 = bit3 & 1;
- uint bit4 = n >> 4;
- bit4 = bit4 & 1;
- uint bit5 = n >> 5;
- bit5 = bit5 & 1;
- //Console.WriteLine("{0}{1}{2}",bit5, bit4, bit3);
- uint bit24 = n >> 24;
- bit24 &= 1;
- uint bit25 = n >> 25;
- bit25 &= 1;
- uint bit26 = n >> 26;
- bit26 &= 1;
- //Console.WriteLine("{0}{1}{2}", bit26, bit25, bit24);
- //Now that I have every bit seperately I will try to exchange their positions while the their names(variables) won't be changed
- uint mask0 = bit3<<24;
- n = (uint)(n &(~(1<<24)));
- uint result = mask0 ^ n;
- uint mask1 = bit4<<25;
- n = (uint)(n&(~(1<<25)));
- result = mask1 ^ n;
- uint mask2 = bit5 << 26;
- n = (uint)(n & (~(1 << 26)));
- result = mask2 ^ n;
- //Now I have transfered bits at poistion 3,4 and 5 to 24,25 and 26 so I have to the the same but backwards
- uint mask3 = bit24 << 3;
- n = (uint)(n & (~(1 << 3)));
- result = result & mask3;
- uint mask4 = bit25 << 4;
- n = (uint)(n & (~(1 << 4)));
- result = result ^ mask4;
- uint mask5 = bit26 << 5;
- n = (uint)(n & (~(1 << 5)));
- result = result ^ mask5;
- Console.WriteLine(result);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement