Write a C expression (or a collection of sequential expressions) that will swap
ID: 3880325 • Letter: W
Question
Write a C expression (or a collection of sequential expressions) that will swap the mth and nth byte of the 64-bit quantity (stored as a 64-bit integer, but is really 8 ascii characters).
For this problem the index of the least significant byte is 0, and the index of the most significant byte is 7 (so 0 <= n,m <= 7). So if x = “hi calss” = 0x68692063616C7373 (a 64-bit quantity), and we want to swap the ‘a’ and the ‘l’ to get “hi class” we could have n equals 3 and m equals 2, the C expression(s) would return 0x686920636C617373 = “hi class”.
You cannot 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.
Explanation / Answer
We have used char array of 8 elements (64 bit) to store the number and XOR operation to SWAP the numbers.
Swap algorithm
C Code:
#include <stdio.h>
int main()
{
char exp[8] = "hi calss";
int m,n;
printf("Exp - %s ",exp);
printf("Please enter the first bit you wana swap ");
scanf("%d",&m);
printf("Please enter the second bit you wana swap ");
scanf("%d",&n);
/*swap logic using bitwise XOR*/
exp[m] = exp[m] ^ exp[n];
exp[n] = exp[m] ^ exp[n];
exp[m] = exp[m] ^ exp[n];
printf("After Swap - %s ", exp);
}
----------------------------------------------------------------------------------------------------------------------------------------------------
Output screenshot:
./a.out
Exp - hi calss
Please enter the first bit you wana swap
4
Please enter the second bit you wana swap
5
After Swap - hi class
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.