(7条消息) C字符串 与 uint32类型互相转换
- 字符串转换为 unsigned int 类型
/*将传入的字符串转换为无符号的的32位整形 *@param: str : 传入的字符串 *retval: The converted value.*/static unsigned int atoui(const char *str);unsigned int atoui(const char *str){ unsigned int result = 0, i = 0; char *tmp = NULL; for (i = 0; isspace(str[i]) && i < strlen(str); i++)//跳过空白符; ; tmp = str+i; while (*tmp) { result = result * 10 + *tmp - '0'; tmp++; } return result;}
2. 将uint32 类型转换为 C字符串, 默认采用 10进制
char* uitoa(unsigned int n, char *s){ int i, j; i = 0; char buf[20]; memset(buf, 0, sizeof(buf)); do{ buf[i++] = n % 10 + '0';//取下一个数字 } while ((n /= 10)>0);//删除该数字 i -= 1; for (j = 0; i >= 0; j++, i--)//生成的数字是逆序的,所以要逆序输出 s[j] = buf[i]; s[j] = '\0'; return s;}
3. 自定义LOG输出宏函数,
#define myprint( x...) do {char bufMessagePut_Stdout_[1024]; sprintf(bufMessagePut_Stdout_, x); fprintf(stdout, "%s [%d], [%s]\n", bufMessagePut_Stdout_,__LINE__, __FILE__ ); }while (0) int main() { myprint("The num : %d, The string : %s", 98, "nihao"); return 0; } //该函数宏要注意的地方: 宏中的局部参数: bufMessagePut_Stdout_, 不可以与外面的传进参数同名 ,同名时,宏替换会产生歧义:sprintf(bufMessagePut_Stdout_, "%s", bufMessagePut_Stdout_);此时: 前后bufMessagePut_Stdout_应代表不同的参数类型及意义,而程序上并不会这样认为.
4.将C风格 16进制的字符串 转换为十进制(即: 默认字符串中存的内容为 16进制数据)
//获取x的y次方; x^yunsigned int power(int x, int y){ unsigned int result = 1; while (y--) result *= x; return result;}//将字符串的内容转换为 16进制unsigned int hex_conver_dec(char *src){ char *tmp = src; int len = 0; unsigned int hexad = 0; char sub = 0; while (1) { if (*tmp == '0') //去除字符串 首位0 { tmp++; continue; } else if (*tmp == 'X') { tmp++; continue; } else if (*tmp == 'x') { tmp++; continue; } else break; } len = strlen(tmp); for (len; len > 0; len--) { sub = toupper(*tmp++) - '0'; if (sub > 9) sub -= 7; hexad += sub * power(16, len - 1); } return hexad;}int main(){ hex_conver_dec("31"); //49 hex_conver_dec("abcd02"); //11259138}
5.在一块内存中查找子串位置:该函数主要是为了在二进制文本中进行查找操作。
//获取字符流中的指定子串的位置char* memstr(char* full_data, int full_data_len, char* substr) { if (full_data == NULL || full_data_len <= 0 || substr == NULL) { return NULL; } if (*substr == '\0') { return NULL; } int sublen = strlen(substr); int i; char* cur = full_data; int last_possible = full_data_len - sublen + 1; for (i = 0; i < last_possible; i++) { if (*cur == *substr) { //assert(full_data_len - i >= sublen); if (memcmp(cur, substr, sublen) == 0) { //found return cur; } } cur++; } return NULL; }
6. 查看指定目录下的文件是否存在
bool if_file_exist(const char *filePath){ if(filePath == NULL) assert(0); if(access(filePath, F_OK) == 0) return true; return false;}
7. 将unsigned int 转换为16进制C字符串
char *unsigned_int_to_hex(unsigned int number, char *hex_str){ char b[17] = { "0123456789ABCDEF" }; int c[8], i = 0, j = 0, d, base = 16; do{ c[i] = number % base; i++; number = number / base; } while (number != 0); hex_str[j++] = '0'; hex_str[j++] = 'X'; for (--i ; i >= 0; --i, j++) { d = c[i]; hex_str[j] = b[d]; } hex_str[j] = '\0'; return hex_str;}
赞 (0)