一串字符串转换为ascii
Given an ASCII string (char[]) and we have to convert it into BYTE array (BYTE[]) in C.
给定一个ASCII字符串(char []),我们必须将其转换为C语言中的BYTE数组(BYTE [])。
Logic:
逻辑:
To convert an ASCII string to BYTE array, follow below-mentioned steps:
要将ASCII字符串转换为BYTE数组,请执行以下步骤:
Extract characters from the input string and get the character's value in integer/number format using %d format specifier, %d gives integer (number) i.e. BYTE value of any character.
从输入字符串中提取字符,并使用%d格式说明符以整数/数字格式获取字符的值, %d给出整数(数字),即任何字符的BYTE值。
Add these bytes (number) which is an integer value of an ASCII character to the output array.
将这些字节(数字)(它是ASCII字符的整数值)添加到输出数组中。
After each iteration increase the input string's loop counter (loop) by 1 and output array's loop counter (i) by 1.
每次迭代后,将输入字符串的循环计数器( loop )增大1,将输出数组的循环计数器( i )增大1。
Example:
例:
Input: "Hello world!"
Output:
72
101
108
108
111
32
119
111
114
108
100
33
C程序将ASCII char []转换为BYTE数组 (C program to convert ASCII char[] to BYTE array)
In this example, ascii_str is an input string that contains "Hello world!", we are converting it to a BYTE array. Here, we created a function void string2ByteArray(char* input, BYTE* output), to convert ASCII string to BYTE array, the final output (array of integers) is storing in arr variable, which is passed as a reference in the function.
在此示例中, ascii_str是包含“ Hello world!”的输入字符串。 ,我们正在将其转换为BYTE数组。 在这里,我们创建了一个函数void string2ByteArray(char * input,BYTE * output) , 将ASCII字符串转换为BYTE array ,最终输出(整数数组)存储在arr变量中,该变量作为函数中的引用传递。
Note: Here, we created a typedef BYTE for unsigned char data type and as we know an unsigned char can store value from 0 to 255.
注意:在这里,我们为无符号字符数据类型创建了一个typedef BYTE ,众所周知, 无符号字符可以存储0到255之间的值。
Read more: typedef in C, unsigned char in C
: C语言中的typedef,C语言中的unsigned char
#include <stdio.h>
#include <string.h>
typedef unsigned char BYTE;
//function to convert string to byte array
void string2ByteArray(char* input, BYTE* output)
{
int loop;
int i;
loop = 0;
i = 0;
while(input[loop] != '\0')
{
output[i++] = input[loop++];
}
}
int main(){
char ascii_str[] = "Hello world!";
int len = strlen(ascii_str);
BYTE arr[len];
int i;
//converting string to BYTE[]
string2ByteArray(ascii_str, arr);
//printing
printf("ascii_str: %s\n", ascii_str);
printf("byte array is...\n");
for(i=0; i<len; i++)
{
printf("%c - %d\n", ascii_str[i], arr[i]);
}
printf("\n");
return 0;
}
Output
输出量
ascii_str: Hello world!
byte array is...
H - 72
e - 101
l - 108
l - 108
o - 111
- 32
w - 119
o - 111
r - 114
l - 108
d - 100
! - 33
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-byte-array-in-c.aspx
一串字符串转换为ascii