Write a C program that will swap any two nibbles of a long int x (64-bit integer
ID: 3743971 • Letter: W
Question
Write a C program that will swap any two nibbles of a long int x (64-bit integer). A nibble is a four-bit aggregation. There are two nibbles in a byte. For this problem the index of the least significant nibble is 0, and the index of the most significant nibble is 15 (so 0 <= m, n <= 15). So, if x = 0x0123456789ABCDEF (a 64-bit integer), and if you swap two nibbles say that are at the 0th and 15th index, x would now be x=0xF123456789ABCDE0. You are not allowed to use division, multiplication, or modulus, relative comparisons (<, >, <=, >=), loops, switches, function calls, macros, conditionals (if or ?:) You are allowed to use all bit level and logic operations, left and right shifts, addition and subtraction, equality and inequality tests, integer constants (<=255), INT_MIN and INT_MAX, and casting between data types. (20 points).
Explanation / Answer
// Comment if u have any doubt
int main() {
long long int y, x = 0x0123456789ABCDEF;
int i, j;
printf("Enter 1st position : ");
scanf("%d", &i);
printf(" Enter 2nd position : ");
scanf("%d", &j);
unsigned long long int m = 0xF;
unsigned long long int k = m << (i << 2); // Find 1st nibble position
unsigned long long int l = m << (j << 2); // Find 2nd nibble position
unsigned long long int u = (x & k); // Extract 1st nibble and store in a variable
unsigned long long int v = (x & l); // Extract 2nd nibble and store in a variable
u = (u >> (i << 2)); // Bring that 1st nibble data to the end
v = (v >> (j << 2)); // Bring that 2nd nibble data to the end
k = ~k;
l = ~l;
y = x & k; // Make 1st nibble position bits as zero ; we will replace those zero bits with 2nd nibble bits
y = y & l; // Make 2nd nibble position bits as zero ; we will replace those zero bits with 1st nibble bits
y = y | u << (j << 2);
y = y | v << (i << 2);
printf(" Input number : 0x%16llx ",x);
printf("Swapped number :0x%16llx ", y);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.