[C programming] I need help with writing a method that takes in a character, for
ID: 3588332 • Letter: #
Question
[C programming]
I need help with writing a method that takes in a character, for example, A and a 2D array that consists of 'S' meaning swap or 'N' meaning don't swap. The 2D array will look something like this
SNSN
SNSN
SNSN
SNSN
This method iterates through the 2D array, in this case, table and if for example, table[3][0] == 'S' that means swap bits 7 and 6. The first row in the 2D array deals with bits in position 7 and 6, second-row deals with bits 5 and 4, third row deals 3 and 2, and fourth row deals with bits 1 and 0. The code below is what I have so far. Please provide code and explain how swapping bits work. I'm not knowledgeable on bit manipulation and how it works.
char encrypt(char ch, int table[4][4])
{
char ret;
int col, row;
for(col = 0; col < 4; col++)
{
for(row = 0; row < 4; row++)
{
if(table[row][col] == 'S')
{
if(row == 0)
{
//swap bits 7 and 6 in ch
}
else if(row == 1)
{
// swap bits 5 and 4 in ch
}
else if(row == 2)
{
// swap bits 3 and 2 in ch
}
else if(row == 3)
{
// swap bits 1 and 0 in ch
}
}
}
}
return ret;
}
Explanation / Answer
char encrypt(char ch, int table[4][4])
{
char ret;
int col, row;
for(col = 0; col < 4; col++)
{
for(row = 0; row < 4; row++)
{
if(table[row][col] == 'S')
{
if(row == 0)
{
//swap bit 7 and 6
b7 = ch & 128;
b6 = ch & 64;
b = b7 >> 1 | b6 << 1;
ch = ch & 63 | b;
}
else if(row == 1)
{
//swap bit 5 and 4
b5 = ch & 32;
b4 = ch & 16;
b = b5 >> 1 | b4 << 1;
ch = ch & 207 | b;
}
else if(row == 2)
{
//swap bit 3 and 2
b3 = ch & 8;
b2 = ch & 4;
b = b3 >> 1 | b2 << 1;
ch = ch & 243 | b;
}
else if(row == 3)
{
//swap bit 1 and 0
b1 = ch & 2;
b0 = ch & 1;
b = b1 >> 1 | b0 << 1;
ch = ch & 252 | b;
}
}
}
}
return ret;
}
If you have any doubt, please let me know!
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.