一、代码如下
(一)十六进制字符串转十进制整数
#include<stdio.h>
// 把一个十六进制字符转成十进制整数
int hexToInt(char hexs[]){
int index;
int k = 0;
for(k = 0; ; k++) {
if(hexs[k] == '\0') {
index = k;
break;
}
}
int temp = 0;
int result = 0;
int move = 0;
for(k = index - 1; k >= 0; k--) {
temp = hexs[k];
if(temp >= '0' && temp <= '9') {
result = result | ((temp - 48) << (4 * move));
} else if(temp >= 'A' && temp <= 'Z') {
result = result | ((temp - 55) << (4 * move));
}
move = move + 1;
}
return result;
}
(二)整数转十六进制字符串
// 把一个整数转成十六进制字符
void toHex(int c, char result[]) {
char letters[] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
result[0] = letters[(c >> 28) & 0x0F];
result[1] = letters[(c >> 24) & 0x0F];
result[2] = letters[(c >> 20) & 0x0F];
result[3] = letters[(c >> 16) & 0x0F];
result[4] = letters[(c >> 12) & 0x0F];
result[5] = letters[(c >> 8) & 0x0F];
result[6] = letters[(c >> 4) & 0x0F];
result[7] = letters[c & 0x0F];
result[8] = '\0';
}
(三)求字符串的长度
// 求字符串的字节长度
int len(char target[]) {
int k = 0;
int len = 0;
for(k = 0; target[k] != 0; k++) {
len = len + 1;
}
return len;
}
(四)在字符串左边填充指定的字符
// 高位填充字符;
// target是目标数组
// c是填充的字符类型
// totalLen是期望的字符总位数
void fill(char target[], char c, int totalLen) {
int len(char[]);
int last_len = len(target);
if(totalLen > last_len) {
int k = 0;
int step = totalLen - last_len;
// 往后面移动step位
for(k = totalLen - 1; k >= step; k--) {
target[k] = target[k - step];
}
// 填充内容为c;
for(k = 0; k < step; k++) {
target[k] = c;
}
// 设置空字符
target[totalLen] = '\0';
}
}
(五)转成大写
// 字母大写
void upper(char c[]){
int k = 0;
while(c[k] != '\0') {
if(c[k]>= 'a' && c[k] <= 'z') {
c[k] = c[k] - 32;
}
k++;
}
}
(六)转成小写
// 字母小写
void lower(char c[]){
int k = 0;
while(c[k] != '\0') {
if(c[k]>= 'A' && c[k] <= 'Z') {
c[k] = c[k] + 32;
}
k++;
}
}
(七)截取字符串
// 截取字符串
void substr(char target[], char result[], int offset, int end) {
int k = 0;
for(k = offset; k < end; k++) {
result[k - offset] = target[k];
}
result[k] = '\0';
}
(八)文件中读取UTF-8字符
// 从文件里读取一个UTF-8字符
void readUTF8(FILE* p, char buff[]) {
char c1 = 0;
char c2 = 0xC0;
char c3 = 0xE0;
char c4 = 0xF0;char c = 0;
// 按照UTF-8的格式读取
if(!feof(p)) {
c = fgetc(p);
// 第一种
if((c & c4) == c4){
buff[0] = c;
buff[1] = fgetc(p);
buff[2] = fgetc(p);
buff[3] = fgetc(p);
buff[4] = '\0';
} else if((c & c3) == c3){
buff[0] = c;
buff[1] = fgetc(p);
buff[2] = fgetc(p);
buff[3] = '\0';
} else if((c & c2) == c2){
buff[0] = c;
buff[1] = fgetc(p);
buff[2] = '\0';
} else if((c & c1) == c1) {
buff[0] = c;
buff[1] = '\0';
}
} else {
buff[0] = '\0';
}
}