1. C語言編寫異或函數


1.函數功能
代碼實現將一個字符串,按16個字符一組,分為若干組;第一組與第二組異或,結果在與第三組異或,一次類推得出最終異或結果。
2. 代碼實現
//xor_test.c 文件名
#include <stdio.h>
#include <memory.h>
#include <string.h>
 
#define MAX_LENGTH 1024
#define XOR_LENGTH 16
 
//將字符轉換為整形
int char_to_int(char ch);
 
int main(int argc, char *argv[])
{
//保存需要異或的字符串
char xor_str[MAX_LENGTH] = {'\0'};
int pos = 0;//字符指針當前所指位置
char buffer[XOR_LENGTH + 1] = {'\0'};
char str1[XOR_LENGTH + 1] = {'\0'};
char str2[XOR_LENGTH + 1] = {'\0'};
int num1 = 0;
int num2 = 0;
int result = 0;
int i = 0;
int count = 0;//實際字符計數器
char ch = '\0';
 
printf("input: ");
fgets(xor_str, MAX_LENGTH, stdin);//可以吸收空格,單無法吸收回車、換行
//函數原型: char *fgets(char *buf, int bufsize, FILE *stream);
// scanf("%s", xor_str);
 
//去掉需要異或字符串里的空格
while(xor_str[i] != '\0'){
ch = xor_str[i];
if(ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t'){
i++;
continue;
}else{
memcpy(xor_str + count++, xor_str + i++, 1);
}
}
 
//將字符串末尾多余的空格全部置空
 memset(xor_str + count, '\0', MAX_LENGTH - count);
 
 
//將需要異或的字符個數,用0補齊位16的整數倍
while(count % XOR_LENGTH != 0){
memcpy(xor_str + count++, "0", 1);
// printf("count: %d ", count);
}
 
//將需要異或字符串前16個字符,拷到str1字符數組中,僅此一次並將指針移至16位置
for(pos = 0; pos < XOR_LENGTH; pos++){
memcpy(str1 + pos, xor_str + pos, 1);
printf("%c", *(str1 +pos));
}
putchar('\n');
 
//循環異或,得出最終結果
for(; pos < strlen(xor_str); pos++){
memcpy(str2 + (pos % XOR_LENGTH), xor_str+ pos, 1);
printf("%c", *(str2 + (pos % XOR_LENGTH)));
//pos大於16是為了從src源字符串中,復制16-31位置共16個字符到str2中,不至於還沒復制就循環了;從src取第二批16字符到str2時pos=31,取第三批16字符到str2時pos=47,所以pos需要加1
if((pos > XOR_LENGTH) && ((pos+1) % XOR_LENGTH == 0)){
for(i = 0; i < XOR_LENGTH; i++){
num1 = char_to_int(str1[i]);//調用函數,將字符轉換為整形
num2 = char_to_int(str2[i]);
result = num1 ^ num2;//異或
// sprintf(str1 + i, "%0x", result);
sprintf(buffer + i, "%0x", result);//將單個異或結果,按十六進制追加拷入buffer,形成兩個字符串異或的結果
}
memcpy(str1, buffer, XOR_LENGTH);//將兩個字符串異或結果,在拷入str1字符數組
printf("\tresult: %s\n", str1);//輸出異或結果
}
}
 
return 0;
}
 
//將字符轉換為整形
int char_to_int(char ch)
{
switch(ch){
case '0':
return 0;
case '1':
return 1;
case '2':
return 2;
case '3':
return 3;
case '4':
return 4;
case '5':
return 5;
case '6':
return 6;
case '7':
return 7;
case '8':
return 8;
case '9':
return 9;
case 'a':
return 10;
case 'b':
return 11;
case 'c':
return 12;
case 'd':
return 13;
case 'e':
return 14;
case 'f':
return 15;
default:
return -1;
}
 
return -1;
}
 
3. 運行結果
終端運行:
[centos@localhost study]$ vi xor_test2.c 
[centos@localhost study]$ gcc xor_test2.c -Wall
[centos@localhost study]$ ./a.out 
input: ba1d1b4056c302e66222032011004560044D4912120514999114400104996222543221987655
ba1d1b4056c302e6
6222032011004560 result: d83f186047c34786
044D491212051499 result: dc7f517255c6531f
9114400104996222 result: 4d6b1173515f313d
5432219876550000 result: 195930eb270a313d
[centos@localhost study]$ 
 
注:最后一組不滿16字符,自動用0補全。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM