C - 使用最低有效位编码和解码消息

问题描述 投票:0回答:1

我的任务是使用最低有效位对消息进行解码和编码。消息以最低有效位加密。要解码一个字母,我必须检查八个连续字节(八个数字)。我必须在联合中使用位字段来进行此练习。我的程序中的解码工作正常,但编码有问题。 函数编码不编码任何内容。这个功能有什么问题吗?


#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>

union bit_set
{
    signed char x;
    struct tab
    {
        unsigned char one: 1;
        unsigned char two: 1;
        unsigned char three: 1;
        unsigned char four: 1;
        unsigned char five: 1;
        unsigned char six: 1;
        unsigned char seven: 1;
        unsigned char eight: 1;
    } tab;
};

int decode(const char * array2, char *txt)
{
    union bit_set bit_set;
    
    int i = 0;
    int j = 0;
    while(*(array2 + i) != '\0')
    {
        signed char number = 0;
        for(int k = 0; k < 8; k++)
        {
            number = number << 1;
            
            bit_set.x = *(array2 + i);
            number = number + bit_set.tab.one;
            i++;
        }
        *(txt + j) = (char)number;
       
        if(*(txt+j) == 0)
        {
            break;
        }
        j++;   
    }
    return 0;
}

int encode(const char *input, char *txt)
{
    int i = 0;
    int j = 0;
    int len = strlen(input);
    
    while(j <= len)
    {
        union bit_set bit_set;
        bit_set.x = (signed char)*(input + j);
        for(int k = 0; k < 8; k++)
        {
            *(txt+i) &= 0xFE;
            *(txt+i) += bit_set.tab.eight;
            *(txt + i) <<= 1;
            
        }
        i++;
        j++;
    }
    int h = 0;
    while(h < 1000)
    {
        printf("%hhu ", *(txt + h));
        h++;
    }

    return 0;
}

int main()
{
    char msg[10000] = {0};
    char array[31] = "p"; //text for encode
    char array2[10000] = {100, 193, 113, 189, 184, 112, 148, 2, 244, 53, 97, 96, 100, 82, 96, 85, 64, 97, 97, 226, 56, 191, 217, 51, 76, 19, 155, 96, 236, 247, 10, 181, 
82, 42, 188, 4, 78, 178, 210, 86, 90, 110, 94}; //word 'page' for decode
    
    encode(array, msg);
    
    //decode(array2, msg);

    //printf("%s", msg);

    return 0;
}

c encryption bit unions
1个回答
0
投票

我们看一下内循环里面的语句:

*(txt+i) &= 0xFE;
*(txt+i) += bit_set.tab.eight;
bit_set.x <<= 1;
i++;

前两个语句将分配给

txt[i]
。第三个对于这个问题来说并不重要。第四个语句是问题:您增加
i
,以便下次您不会更新
txt
的相同索引,而是更新下一个。

这导致只为

txt
中的每个元素设置一个位。

i++
可能应该在循环之外。

© www.soinside.com 2019 - 2024. All rights reserved.