【发布时间】:2014-06-27 23:05:41
【问题描述】:
我试图在一个字符中交换两个位值。我已经深入研究了这一点,此时我的代码相当混乱。我有一个嵌套的for循环,一个遍历字符数组,查看每个字符,将单个字符的位放入数组中,执行一些交换,最后将当前字符(字符数组中的位置)设置为整数数组。
我希望我可以将当前 char(在 char 数组中)更新为 int 数组位值,从而生成新的 char。
基本上,目标是交换 char 中的位并生成新的 char。
我声明的变量...
unsigned char s = 's';
FILE *fp;
char ch;
int count = 0;
//used in a loop to create an array of chars
unsigned char *load = malloc(sizeof(char));
int i = 0;
char temp, temp2;
int temp3, temp4;
int w, v;
int array[7];
v = 0;
for (i = 0; i < count; ++i)
{
for (w = 7; w >= 0; w--)
{
array[v] = (1 & (load[i] >> w));
}
temp3 = array[5];
array[5] = array[1];
array[1] = temp3;
temp4 = array[0];
array[0] = array[4];
array[4] = temp4;
//here I'm trying to set a char array to an int array.
//would static casting the int array to char work?
//I can't find a way to convert it.
load[i] = array;
}
我正在尝试为无符号字符数组中的每个字节执行此交换。
感谢您的宝贵时间,非常感谢。
编辑:发布整段代码
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[]) {
//unsigned char *s = "S";
unsigned char s = 's';
FILE *fp;
char ch;
int count = 0;
unsigned char *load = malloc(sizeof(char));
int i = 0;
char temp, temp2;
int temp3, temp4;
int w, v;
int array[7];
v = 0;
fp = fopen("file", "r");
if (fp == NULL)
{
perror("Exiting, an error occured\n");
exit(EXIT_FAILURE);
}
//print encrypted file
while ((ch = fgetc(fp)) != EOF)
{
printf("%c", ch);
++count;
}
fclose(fp);
printf("\n\n");
fp = fopen("file", "r");
if (fp == NULL)
{
perror("exiting\n");
exit(EXIT_FAILURE);
}
i = 0;
//load encrypted file into usigned char array
while ((ch = fgetc(fp)) != EOF)
{
load[i++] = ch;
}
load[i] = 0;
fclose(fp);
//print unsigned char array in hex
for (i = 0; i < count; ++i)
{
printf("%x ", load[i]);
}
printf("\nNext\n");
//print unsigned char array
for (i = 0; i < count; ++i)
{
printf("%c ", load[i]);
}
printf("\n\n");
//byte swaps through every 4th byte in the unsignged char array until end
for (i = 3; i < count;)
{
temp = load[i-1];
load[i-1] = load[i];
load[i] = temp;
i = i + 4;
}
//print new unsigned char array
for (i = 0; i < count; ++i)
{
printf("%c ", load[i]);
}
printf("\n\n");
//bit swaps on every byte in the unsigned char array
//not working
for (i = 0; i < count; ++i)
{
for (w = 7; w >= 0; w--)
{
array[v] = (1 & (load[i] >> w));
}
temp3 = array[5];
array[5] = array[1];
array[1] = temp3;
temp4 = array[0];
array[0] = array[4];
array[4] = temp4;
load[i] = array;
}
//XOR every 4th byte in the unsigned char array
for (i = 3; i < count;)
{
temp = (load[i-1] ^ s);
temp2 = (load[i] ^ s);
load[i-1] = temp;
load[i] = temp2;
i = i + 4;
}
//print the decrypted message
for (i = 0; i < count; ++i)
{
printf("%c ", load[i]);
}
printf("\n\n");
return 0;
}
【问题讨论】:
-
仅供参考 sizeof(char) 始终为 1
-
for (w = 0; w >= 0; w--)- 奇怪的“循环”。对 malloc 的奇怪评论,它永远不会创建一个超过一个字符的数组。您不能分配给数组,但我真的无法从您的代码中判断该分配应该做什么。 -
我更新了这篇文章,向你展示我是如何使用它来创建一个字符数组的。
-
在循环中 w 应该被设置为 7,它现在可以正确读取了。
-
@user3586343,您似乎误解了“malloc()”零已分配的内存?但是,'malloc()' 不会将内存清零。因此,“加载”将指向具有随机内容的内存(不是一个很好的归零数组)。因此,表达式 '(1 & (load[i] >> w))' 产生的值将是不可预测的。