C language common algorithm 1-data format conversion

Data type conversion and formatted printing

1. Data type conversion
  Data type conversion refers to converting a value of one data type into a value of another data type. In programming, we may need to convert an integer to a floating point number, a string to a number, and so on. This conversion usually involves some arithmetic or logical operations, as well as implicit or explicit conversion of data types
2. Formatting and printing
  Formatting and printing refers to formatting the value of one or more variables into a string for output to screen or file. Formatted printing usually involves some string operations, such as string concatenation, string replacement, format control characters, etc. The purpose of formatted printing is to present data to users in an easy-to-read way, which can include data types such as numbers, text, and dates.

Print data in different formats

In the C language, the format control character of the printf function can be used to print in hexadecimal format. The following are commonly used format control characters:

  • %x or %X: Used to print an integer in hexadecimal format. The lowercase letter x indicates that the output hexadecimal number is a lowercase letter (a f), and the uppercase letter X indicates that the output hexadecimal number is an uppercase letter (A F).
  • %#x or %#X: Same as %x or %X, but prefixed with "0x" or "0X" before the output result.
  • %hx or %hX: Used to print a short type integer (ie 16-bit integer) in hexadecimal format.
  • %#hx or %#hX: Same as %hx or %hX, but will add "0x" or "0X" prefix before the output result.
  • %lx or %lX: used to print a long type integer (ie 32-bit integer) in hexadecimal format.
  • %#lx or %#lX: Same as %lx or %lX, but will add "0x" or "0X" prefix before the output result.
    Example:
#include <stdio.h>
int a = 255;
int b = 0x7fff;
int c = 0x12345678;

int main(void)
{
    
    
    printf("a = %d\r\n",a);
    printf("a = %x\r\n",a);
    printf("a = %X\r\n",a);
    printf("a = %#X\r\n",a);
    printf("a = %hX\r\n",a);
    printf("a = %lX\r\n",a);

    printf("b = %d\r\n",b);
    printf("b = %x\r\n",b);

    printf("c = %d\r\n",c);
    printf("c = %x\r\n",c);

    return 0;
}
[result]
a = 255
a = ff
a = FF
a = 0XFF
a = FF
a = FF
b = 32767
b = 7fff
c = 305419896
c = 12345678

 
不同的打印格式表示的都是同一个数字,只不过就是格式不同罢了。

Convert the value in the string 字符to the corresponding decimal (or hexadecimal) integer value

/**
*@brief	   将 ASCII 字符转换为十六进制数值(或者十进制数值)
*@param		c: 要转换的字符
*@return	返回:返回一个 char 类型的值,表示对应的十六进制数值(或者十进制数值)
*/
char c2d(uint8 c)
{
    
    
	if (c >= '0' && c <= '9')   // 如果是数字字符
		return c - '0'; 		// 直接转换为数字
	if (c >= 'a' && c <= 'f')   // 如果是小写字母
		return 10 + c -'a';     // 转换为数字(a~f对应10~15)
	if (c >= 'A' && c <= 'F')   // 如果是大写字母
		return 10 + c -'A';     // 转换为数字(A~F对应10~15)

	return (char)c;             // 其他字符返回本身
}

c2dIt is mainly operated on a single character, and the output is also a single result, one-to-one correspondence, so it cannot directly operate on a string, and it is aimed at a single character. When operating on a string, you need to use a pointer to take out a single character operation.

Example:

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


int main()
{
    
    
	char hex_str[] = "1aF3";
    uint8_t hex_len = sizeof(hex_str) - 1; // 计算字符串长度
    uint16_t hex_num[hex_len]; // 定义存储十六进制数字的数组

    // 把每个字符转换为对应的十六进制数字
    for (int i = 0; i < hex_len; i++) {
    
    
        hex_num[i] = c2d(hex_str[i]);
    }

    // 输出转换后的数字
    for (int i = 0; i < hex_len; i++)
    {
    
    
        printf("%04x ", hex_num[i]);  //打印对应的十六进制样式展示的数据     
    }
    printf("\r\n");
    for (int i = 0; i < hex_len; i++) 
    {
    
    
        printf("%d ", hex_num[i]);    //打印对应的十进制样式展示的数据
    }
    
    return 0;
}
[result]
0001 000a 000f 0003
1 10 15 3
    
倘若将其中的”1aF3“换成”1aZ3“的话就无法转换 不复合十六进制类型要求的范围 

Convert integer 字符串to integer (decimal style or hexadecimal style)

int atoi(const char *str)
describe The C library function int atoi(const char *str) converts the string pointed to by the parameter str into an integer (the type is int).
statement int atoi(const char *str), called in the #include <stdlib.h> function
parameter str – The string to convert to an integer.
return value The function returns the converted long integer, or zero if no valid conversion was performed.

atoiis array to integeran acronym for English. atoi()The parameter string will be scanned str, and if the first character is not a number or a sign, it will return zero, otherwise it will start to perform type conversion , and then stop converting when a non-number or terminator is detected /0 , and return an integer.

Example:

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

int val;
char str1[20] = "1122334";
char str2[20] = "baidu";
int main(void)
{
    
    
    val = atoi(str1);
    printf("val = %d\r\n",val);
    printf("val = %#x\r\n",val);
    
    val = atoi(str2);
    printf("val = %d\r\n",val);

    return 0;
}

[result]
val = 1122334
val = 0x11201e
val = 0

Only convert decimal values, directly convert to decimal values ​​(or hexadecimal style), this conversion is字符对整数。

Convert a string in hexadecimal format to decimal

describe The C library function long int strtol(const char *str, char **endptr, int base) converts the string pointed to by the parameter str into a long integer (type long int) according to the given base, and the base must be between Between 2 and 36 (inclusive), or the special value 0.
statement long int strtol(const char *str, char **endptr, int base)
parameter str – the string to convert to a long integer. endptr – a reference to an object of type char* whose value is set by the function to the next character after the value in str. base – The base, must be between 2 and 36 (inclusive), or the special value 0.
return value The function returns the converted long integer, or a zero value if no valid conversion was performed.

Example 1:

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

int main() {
    
    
    char* hex_str = "1A7F"; // 十六进制格式的字符串
    long decimal = strtol(hex_str, NULL, 16); // 调用strtol()函数将十六进制字符串转换为十进制整数
    printf("Hexadecimal: %s\n", hex_str);
    printf("Decimal: %ld\n", decimal);
    return 0;
}
[result]
Hexadecimal: 1A7F
Decimal: 6783

Example 2:

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

int main()
{
    
    
   char str[30] = "2030300 This is test";
   char *ptr;
   long ret;

   ret = strtol(str, &ptr, 10);
   printf("数字(无符号长整数)是 %ld\n", ret);
   printf("字符串部分是 |%s|", ptr);

   return(0);
}
[result]
数字(无符号长整数)是 2030300
字符串部分是 | This is test |

Convert a long integer (long) to a string

char* ltoa(long num, char* str, int base);
  • "num" is the long integer to be converted;
  • "str" ​​is a character array used to store the converted string;
  • "base" is the base of the conversion, which can be 2, 8, 10 or 16.

The function converts the long integer "num" to a string in base "base" and stores the result in "str". The function returns a pointer to "str" ​​if the conversion was successful, otherwise it returns NULL.

Example:

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

int main() {
    
    
    long num = 123456789;
    char str[20];
    ltoa(num, str, 10); // 将长整型数转换成十进制字符串
    printf("Long integer: %ld\n", num);
    printf("String: %s\n", str);
    return 0;
}
[result]
Long integer: 123456789
String: 123456789

The modified atoi()function is modified tomyatoi()

Note:

  • atoi()The returned data type is , so it cannot exceed the range int类型when convertingstr
  • This function will skip spaces when converting, and start converting when numbers and signs are encountered
  • end glyph end encountered \0last
// 这个函数接收一个字符串作为输入,并将其转换为整数值
// 然后将整数值返回
// 字符串必须只包含数字字符,或者以符号字符开头
    
/*调整uint8_t 为int 则可以获得更大的数据转换 uint8_t 只能转换0-255*/
uint8_t myatoi(const char *str)
{
    
    
    int s = 0; // 要返回的整数值
    uint8_t flag = 0; // 用于跟踪数字是否为负数

    // 忽略前导空格
    while (*str == ' ')
    {
    
    
        str++;
    }

    // 检查数字是否为负数或正数
    if (*str == '-' || *str == '+')
    {
    
    
        if (*str == '-')
            flag = 1; // 将标志设置为负数
        str++; // 将指针移动到符号字符的下一个字符
    }

    // 将数字字符转换为整数值
    while (*str >= '0' && *str <= '9')
    {
    
    
        // 将当前值乘以10,然后加上当前数字的值
        s = s * 10 + (*str - '0');
        str++; // 将指针移动到下一个字符
        if (s < 0) // 检查是否溢出
        {
    
    
            s = 2147483647; // 将值设置为最大整数值
            break; // 退出循环
        }
    }

    // 返回整数值,根据需要考虑符号
    return s * (flag ? -1 : 1);
}

Example:

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


uint16_t myatoi(const char *str)
{
    
    
	int s = 0;
	uint8_t falg = 0;
	
	while(*str==' ')
	{
    
    
		str++;
	}
 
	if(*str=='-'||*str=='+')
	{
    
    
		if(*str=='-')
		falg=1;
		str++;
	}
 
	while(*str>='0'&&*str<='9')
	{
    
    
		s=s*10+*str-'0';
		str++;
		if(s<0)
		{
    
    
			s=2147483647;
			break;
		}
	}
	return s*(falg?-1:1);
}

char str[] = "65535";
uint16_t num = 0;
int main(void)
{
    
    
    num = myatoi(str);
    printf("num = %d\r\n",num);
    return 0;   
}
[result]
num = 65535

Guess you like

Origin blog.csdn.net/sinat_41690014/article/details/130285978