c語言中將整數轉換成字符串
Given an ASCII string (char[]) and we have to convert it into Hexadecimal string (char[]) in C.
給定一個ASCII字符串(char []),我們必須在C中將其轉換為十六進制字符串(char [])。
Logic:
邏輯:
To convert an ASCII string to hex string, follow below-mentioned steps:
要將ASCII字符串轉換為十六進制字符串,請執行以下步驟:
Extract characters from the input string and convert the character in hexadecimal format using %02X format specifier, %02X gives 0 padded two bytes hexadecimal value of any value (like int, char).
從輸入字符串中提取字符,并使用%02X格式說明符將其轉換為十六進制格式, %02X為0填充兩個字節的任意值的十六進制值(如int , char )。
Add these two bytes (characters) which is a hex value of an ASCII character to the output string.
將這兩個字節(字符)添加為輸出字符串,這兩個字節是ASCII字符的十六進制值。
After each iteration increase the input string's loop counter (loop) by 1 and output string's loop counter (i) by 2.
每次迭代后,將輸入字符串的循環計數器( loop )增大1,將輸出字符串的循環計數器( i )增大2。
At the end of the loop, insert a NULL character to the output string.
在循環末尾,在輸出字符串中插入一個NULL字符。
Example:
例:
Input: "Hello world!"Output: "48656C6C6F20776F726C6421"
C程序將ASCII char []轉換為十六進制char [] (C program to convert ASCII char[] to hexadecimal char[])
In this example, ascii_str is an input string that contains "Hello world!", we are converting it to a hexadecimal string. Here, we created a function void string2hexString(char* input, char* output), to convert ASCII string to hex string, the final output string is storing in hex_str variable.
在此示例中, ascii_str是包含“ Hello world!”的輸入字符串。 ,我們將其轉換為十六進制字符串。 在這里,我們創建了一個函數void string2hexString(char * input,char * output) , 將ASCII字符串轉換為十六進制字符串 ,最終的輸出字符串存儲在hex_str變量中。
#include <stdio.h>
#include <string.h>
//function to convert ascii char[] to hex-string (char[])
void string2hexString(char* input, char* output)
{
int loop;
int i;
i=0;
loop=0;
while(input[loop] != '\0')
{
sprintf((char*)(output+i),"%02X", input[loop]);
loop+=1;
i+=2;
}
//insert NULL at the end of the output string
output[i++] = '\0';
}
int main(){
char ascii_str[] = "Hello world!";
//declare output string with double size of input string
//because each character of input string will be converted
//in 2 bytes
int len = strlen(ascii_str);
char hex_str[(len*2)+1];
//converting ascii string to hex string
string2hexString(ascii_str, hex_str);
printf("ascii_str: %s\n", ascii_str);
printf("hex_str: %s\n", hex_str);
return 0;
}
Output
輸出量
ascii_str: Hello world!
hex_str: 48656C6C6F20776F726C6421
Read more...
...
Octal literals in C language
C語言的八進制文字
Working with octal numbers in C language
使用C語言處理八進制數
Working with hexadecimal numbers in C language
使用C語言處理十六進制數
翻譯自: https://www.includehelp.com/c/convert-ascii-string-to-hexadecimal-string-in-c.aspx
c語言中將整數轉換成字符串