C语言字符串转ASCII、ASCII转字符串、字符串转数组、sprintf、toascii、类型强转、strtol、atoi

1. 16进制数组转字符串数组 hex_to_str

0x31, 0x32, 0x33, 0x34 转换成 ”31323334“

#include <ctype.h>

size_t hex_to_str(char *pszDest, char *pbSrc, int nLen)
{
    char ddl, ddh;
    for (int i = 0; i < nLen; i++) {
        ddh = 48 + ((unsigned char)pbSrc[i]) / 16;
        ddl = 48 + ((unsigned char)pbSrc[i]) % 16;

        if (ddh > 57) ddh = ddh + 7;
        if (ddl > 57) ddl = ddl + 7;

        pszDest[i * 2] = ddh;
        pszDest[i * 2 + 1] = ddl;
    }
    pszDest[nLen * 2] = '\0';
    return 2 * nLen;
}

int main()
{
    char test_hex[4] = {0x31, 0x32, 0x33, 0x34};
    char test_str[4];

    hex_to_str(test_str, test_hex, 4);
    printf("%s\n", test_str); // 打印 31323334
    return 0;
}

2. 字符串数组转16进制数组 str_to_hex

{‘1’, ‘2’, ‘3’, ‘4’} 转换成 {0x12, 0x34}

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

void str_to_hex(char *pbDest, char *pszSrc, int nLen)
{
    char h1, h2;
    char s1, s2;
    for (int i = 0; i < nLen; i++) {
        h1 = pszSrc[2 * i];
        h2 = pszSrc[2 * i + 1];

        s1 = toupper(h1) - 0x30;
        if (s1 > 9)	s1 -= 7;

        s2 = toupper(h2) - 0x30;
        if (s2 > 9)	s2 -= 7;

        pbDest[i] = ((s1 << 4) | s2);
    }
}

int main()
{
    char test_hex[4] = {0};
    char test_str[4] = {'1', '2', '3', '4'};
    int test_hex_num = 0;
    str_to_hex(test_hex, test_str, 4);

    printf("0x%x\n", test_hex[0]); // 打印0x12
    printf("0x%x\n", test_hex[1]); // 打印0x34
    return 0;
}

3. 字符串数组转长整型数字 strtol()、atoi()、atol()

strtol是标准库函数,转换后的数字 = strtol(待转换的字符串数组, &endptr, base 进制), 字符串数组将转换成 指定base进制的数字。

参数base范围从2至36,或0。参数base代表采用的进制方式,如base值为10则采用10进制,若base值为16则采用16进制等。当base值为0时则是采用10进制做转换,但遇到如’0x’前置字符则会使用16进制做转换、遇到’0’前置字符而不是’0x’的时候会使用8进制做转换。

一开始strtol()会扫描参数nptr字符串,跳过前面的空格字符,直到遇上数字或正负符号才开始做转换,再遇到非数字或字符串结束时(‘\0’)结束转换,并将转换数值返回。参数endptr指向停止转换的位置,若字符串nptr的所有字符都成功转换成数字则endptr指向串结束符’\0’。判断是否转换成功,应检查**endptr是否为’\0’

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>


int main()
{
    char test_str[] = "123456";
    int test_hex = 0x34;
    test_hex = atoi(test_str);
    printf("%d\n", test_hex);

    int test_hex2 = 0x34;
    test_hex2 = strtol(test_str, NULL, 10);
    printf("%d\n", test_hex2);
    return 0;
}

4. 单个字符转数字 char2hex

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

int char2hex(char c, char *x)
{
    if (c >= '0' && c <= '9') {
        *x = c - '0';
    } else if (c >= 'a' && c <= 'f') {
        *x = c - 'a' + 10;
    } else if (c >= 'A' && c <= 'F') {
        *x = c - 'A' + 10;
    } else {
        return -1;
    }

    return 0;
}

int main()
{
    char test_hex_num = 0;
    char2hex('7', &test_hex_num);
    printf("%d\n", test_hex_num); // 打印 7
    return 0;
}

5. 单个数字转字符 hex2char

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

int hex2char(char x, char *c)
{
    if (x <= 9) {
        *c = x + '0';
    } else  if (x <= 15) {
        *c = x - 10 + 'a';
    } else {
        return -1;
    }

    return 0;
}

int main()
{
    char test_char = 0;

    hex2char(7, &test_char);
    printf("%c\n", test_char); // 打印 '7'
    return 0;
}

6. 转8进制

uint8_t u8_to_dec(char *buf, uint8_t buflen, uint8_t value)
{
	uint8_t divisor = 100;
	uint8_t num_digits = 0;
	uint8_t digit;

	while (buflen > 0 && divisor > 0) {
		digit = value / divisor;
		if (digit != 0 || divisor == 1 || num_digits != 0) {
			*buf = (char)digit + '0';
			buf++;
			buflen--;
			num_digits++;
		}

		value -= digit * divisor;
		divisor /= 10;
	}

	if (buflen) {
		*buf = '\0';
	}

	return num_digits;
}

7. ASCII 数字转字符,sprintf

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

int main()
{
    char test_ascii[5] = {0x31, 0x32, 0x33, 0x34, 0x35};
    char test_str[5] = {0};

    sprintf(test_str, "%s", test_ascii);
    printf("%s\n", test_str); // ASCII 数字转字符, 打印 '12345'
    return 0;
}

8. 字符转ASCII,toascii

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

int main()
{
    char test2_str = '6';
    char test2_hex = 0;
    test2_hex = toascii(test2_str);
    printf(" 0x%x\n", test2_hex);// 字符转ASCII, 打印 0x36
    return 0;
}

9. 数据类型强转,ASCII <—>字符

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

int main()
{
    int ascii_hex = 0x34;
    char test2_str = (char) ascii_hex;
    printf(" %c\n", test2_str);// ASCII转字符, 打印 4

    char test = '1';
    int test_num = (int) test;
    printf(" 0x%x\n", test_num);// 字符转ASCII, 打印 0x31
   
    return 0;
}

10. sprintf,格式化输出到字符串中

1.介绍

把格式化的数据写入某个字符串缓冲区
int sprintf(char *string, char *format [,argument,…]);

1.1参数列表

参数描述
string字符数组的指针,存放格式化后的数据
format字符串 ”%[flags][width][.precision][length]specifier“, 指定了格式
argument待格式化的数据,根据不同的 format 字符串,函数可能需要一系列的附加参数,每个参数包含了一个要被插入的值,替换了 format 参数中指定的每个 % 标签。参数的个数应与 % 标签的个数相同
format描述
处理字符方向-负号时表时从后向前处理,默认是从前向后
填空字0表示填0,默认是填空格
字符总宽度最小长度、* 可变
精确度小数点后的浮点数位数、* 可变,在后续参数栏中输入具体长度
转换字符%% 印出百分比符号、 %c 字符输出到缓冲区、%s 字符串输出到缓冲区、%f 精确度数字转成浮点数、%d 整数转成十进位、%o 整数转成八进位、%x 整数转成小写十六进位、%X 大写

1.2返回值

成功,返回写入的字符总数,不包括字符串追加在字符串末尾的空字符、结束字符‘\0’。
失败,返回一个负数。

2.具体使用

2.1 拼接字符串

char str[12];
char str_1[] = "123456";
char str_2[] = "ABCDEF";

sprintf(str, "%s%s", str_1, str_2);
printf("%d, %s\n", strlen(str), str);//1.输出12, 123456ABCDEF

sprintf(str, "%.3s%.3s", str_1, str_2);//精确度设置为3
printf("%d, %s\n", strlen(str), str);//输出6, 123ABC

sprintf(str, "%.*s%.*s", 3, str_1, 3, str_2);
printf("%ld, %s\n", strlen(str), str);
char str[12];
char str_1[] = "123456";
char str_2[] = "ABCDEFGH";
int len1 = strlen(str_1);
int len2 = sizeof(str)/sizeof(char) - len1;

sprintf(str, "%.*s%.*s", len1, str_1, len2, str_2);
printf("%ld, %s\n",  strlen(str), str);

2.2 将参数转换成字符串

sprintf(str, "%08X", 123456);			//1.右对齐,总宽度8,补0
printf("%ld, %s\n", strlen(str), str);	//输出8, 0001E240
sprintf(str, "%-8X", 123456);			//2.左对齐,总宽度8,默认补空格
printf("%ld, %s\n", strlen(str), str);	//输出8, 1E240
sprintf(str, "%-8X", 123456);			//3.左对齐,总宽度8,补0
for(int i=0;i<8;i++) {
    if (str[i] == ' ')
        str[i] = '0';//将默认补的空格替换成‘0’
}
printf("%ld, %s\n", strlen(str), str);//输出8, 1E240000

snprintf
int snprintf(char* dest_str,size_t size,const char* format,…);
将可变个参数(…)按照format格式化成字符串,然后将其复制到str中。
(1) 如果格式化后的字符串长度 < size,则将此字符串全部复制到str中,并给其后添加一个字符串结束符(‘\0’);
(2) 如果格式化后的字符串长度 >= size,则只将其中的**(size-1)**个字符复制到str中,并给其后添加一个字符串结束符(‘\0’),返回值为欲写入的字符串长度

  • 3
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值