我的任务是使用最低有效位对消息进行解码和编码。消息以最低有效位加密。要解码一个字母,我必须检查八个连续的字节(八个数字(。我必须使用联合中的位字段进行此练习。我的程序中的解码非常有效,但我在编码方面有问题。函数编码不编码任何内容。这个函数有什么问题?
#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) != ' ')
{
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;
}
让我们看看内部循环中的语句:
*(txt+i) &= 0xFE;
*(txt+i) += bit_set.tab.eight;
bit_set.x <<= 1;
i++;
前两个语句将分配给txt[i]
。第三个对这个问题来说并不重要。第四种说法是问题:增加i
,这样下次就不会更新txt
的同一索引,而是更新下一个索引。
这导致对于txt
中的每个元素仅设置单个比特。
i++
可能应该在循环之外。