-
Notifications
You must be signed in to change notification settings - Fork 0
/
some_utils.c
110 lines (92 loc) · 2.16 KB
/
some_utils.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#include <string.h>
#include <stdio.h>
int hex2_str(unsigned char *src, int srclen, char *des, int deslen) {
unsigned char Hb;
unsigned char Lb;
if (deslen < srclen * 2) return 0;
memset(des, 0, deslen);
for (int i = 0; i < srclen;i++) {
Hb = (src[i] & 0xF0) >> 4; // 高位
if (Hb <= 9) Hb += 0x30; // 0~9
else if (Hb >= 10 && Hb <= 15) Hb = Hb - 10 + 'A'; // 10~15
else return 0;
Lb = src[i] & 0x0F; // 低位
if (Lb <= 9) Lb += 0x30;
else if (Lb >= 10 && Lb <= 15) Lb = Lb - 10 + 'A';
else return 0;
des[i * 2] = Hb;
des[i * 2 + 1] = Lb;
}
return 1;
}
int str2_hex(char *src, unsigned char *des) {
unsigned char Hb, Lb;
unsigned int len = strlen(src);
for (int i = 0, j = 0; i < len; i++) {
Hb = src[i];
if (Hb >= 'A'&&Hb <= 'F') Hb = Hb - 'A' + 10;
else if (Hb >= '0'&&Hb <= '9') Hb -= 0x30;
else return 0;
i++;
Lb = src[i];
if (Lb >= 'A'&&Lb <= 'F') Lb = Lb - 'A' + 10;
else if (Lb >= '0'&&Lb <= '9') Lb -= 0x30;
else return 0;
des[j++] = (Hb << 4) | Lb;
}
return 1;
}
void print_hex(unsigned char* p){
while (*p){
printf(" %2x",*(p));
p++;
}
}
void str2hex_convert_test() {
unsigned char src[] = { 0x12,0x34,0x56,0x78,0x90,0xab,0xbc,0xcd,0xde,0xef };
char des[21];
hex2_str(src, sizeof(src),des, sizeof(des));
printf("\nsrc :%s ", des);
print_hex(src);
memset(src,0,sizeof(src));
if (str2_hex(des, src)) {
printf("\n convert Ok .");
print_hex(src);
}
else printf("\nconvert failed .");
}
void swap1(int * a,int * b) {
*a = *a + *b;
*b = *a - *b;
*a = *a - *b;
}
void swap2(int * a, int * b) {
*a = *a ^ *b;
*b = *a ^ *b;
*a = *a ^ *b;
}
void swap3(int *a, int *b) {
int temp;
temp = *a;
*a = *b;
*b = temp;
}
int system_mod() {
union {
int a;
char b;
} c;
c.a = 1;
return c.b;
}
void swap123_test() {
unsigned int a = 86, b = 46;
printf("a: %d, b: %d \n", a, b);
swap2(&a, &b);
printf("a: %d, b: %d \n", a, b);
swap1(&a, &b);
printf("a: %d, b: %d \n", a, b);
swap3(&a, &b);
printf("a: %d, b: %d \n", a,b);
printf("return 1 is little mod,0 is big mod :%d \n",system_mod());
}