在C中的char数组内进行位交换

时间:2015-11-02 19:57:08

标签: c arrays bit-manipulation bit bitmask

我正在尝试编写一个读取文本文件的程序,然后根据这些资格对其进行解密:

  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与 字符&#39; R&#39;
  4. 我的程序将文本文件读入名为&#39; message&#39;的动态数组中。下面是我为字节/位交换实现的代码:

    //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");
    

    程序的最终输出将消息的所有字符转换为&#39; R&#39;。因此,如果消息长度为5个字符,则输出为&#34; RRRRR&#34;。

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

1 个答案:

答案 0 :(得分:0)

你获得所有R的原因就在这里......

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);
}