【问题标题】:Bit swapping within a char array in C在 C 中的 char 数组中进行位交换
【发布时间】:2015-11-02 19:57:07
【问题描述】:

我正在尝试编写一个读取文本文件的程序,然后按照以下条件对其进行解密:

  1. 每 4 个字节 <c0,c1,c2,c3> 交换字节 c2 和 c3
  2. 对于每个字节<b7,b6,b5,b4,b3,b2,b1,b0> 交换位 b3 和 b1,以及 交换位 b2 和 b0
  3. 对于每 4 个字节 <c0,c1,c2,c3> XOR 字节 c2 和 c3 与 字符“R”

我的程序将文本文件读入一个名为“消息”的动态数组。下面是我为字节/位交换实现的代码:

//Because chars are 1 byte long, just switch elements of the message array  
int i = 0;
for (i = 0; i < length; i = i+4)
{
    char temp;
    temp = message[i+3];
    message[i+3] = message[i+2];
    message[i+2] = temp;
}

//Second letter of key is 'Y'.  Swap bits b3 and b1, swap bits b2 and b0 in every byte of <b7,b6,b5,b4,b3,b2,b1,b0>
//use bit shifting and bit masks
char mask1 = 0x08; //mask of 00001000 for bit b3
char mask2 = 0x02; //mask of 00000010 for bit b1
char mask3 = 0x04; //mask of 00000100 for bit b2
char mask4 = 0x01; //mask of 00000001 for bit b0

char mask5 = 0xF0; //mask of 11110000 to preserve shifted bits but allow first four through

//and bits together and shift for every byte of message
int s = 0;
for (s = 0; s < length; s = s+1)
{
    char result = ((message[s] & mask1) >> 2 | (message[s] & mask2) << 2);
    char second = ((message[s] & mask3) >> 2 | (message[s] & mask4) << 2);
    message[s] = ((result | second) & mask5);
}

//Third letter of the key is 'R'.  XOR bytes c1 and c0 with k3 of bytes <c0,c1,c2,c3>
int j = 0;
for (j = 0; j < length; j = j+4)
{
    message[j] = message[j] ^ 'R';
    message[j+1] = message[j+1] ^ 'R';
}

//display message
printf("The message is: ");
for (i = 0; i < length; i = i+1)
{
    printf("%c", message[i]);
}
printf("\n");

程序的最终输出将消息的所有字符变为“R”。因此,如果消息长度为 5 个字符,则输出将为“RRRRR”。

我不明白为什么这些交换不起作用!任何提示或见解将不胜感激。

【问题讨论】:

  • 交换位的代码最终将message[s] 设置为零。您应该对该代码使用调试器,或者在循环结束时使用printf 打印出resultsecondmessage[s]
  • message[s] = (message[s] & mask5) | (结果|第二)

标签: c arrays bit-manipulation bit bitmask


【解决方案1】:

你得到所有卢比的原因在这里......

for (s = 0; s < length; s = s+1)
{
    char result = ((message[s] & mask1) >> 2 | (message[s] & mask2) << 2);
    char second = ((message[s] & mask3) >> 2 | (message[s] & mask4) << 2);
    message[s] = ((result | second) & mask5);
}

mask5 清除低四位。

我想你的意思是......

for (s = 0; s < length; s = s+1)
{
    char b3 = message[s] & mask1;
    char b2 = message[s] & mask2;
    char b1 = message[s] & mask3;
    char b0 = message[s] & mask4;

    message[s] &= ~(mask1 | mask2 | mask3 | mask4);
    message[s] |= (b3 >> 2 | b1 << 2 | b2 >> 2 | b0 << 2);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-29
    • 2012-01-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多