[英]Transferring a string of characters in quotes to an array of ascii2 bytes in C
How do I easily convert a string of characters in quotes to an array of ascii2 values? 我如何轻松地将引号中的字符串转换为ascii2值数组?
For example: 例如:
char ST1[5] = "12345";
to 至
char DST1[5] = { 0x31, 0x32, 0x33, 0x34, 0x35 }; //string of bytes
Practically nothing. 几乎没有。
First, remember that string literals such as "12345"
have an extra "null" byte at the end. 首先,请记住,字符串文字如
"12345"
在末尾有一个额外的“空”字节。 So instead of treating this array initialization of "12345"
to an array of 5 elements, it's really an array of 6 elements, so this initialization statement is more appropriate: 因此,与其将
"12345"
此数组初始化处理为包含5个元素的数组, "12345"
将其实际上是包含6个元素的数组,因此此初始化语句更合适:
char ST1[6] = "12345";
Or just simply: 或者只是:
char ST1[] = "12345";
// where the size of "6" is auto inferred. //自动推断为“ 6”的大小。
Which is equivalent to: 等效于:
char DST1[] = {0x31,0x32,0x33,0x34,0x35,0x00};
And once you have an array of 6 elements, you can pass it around as if it had only 5: 一旦拥有6个元素的数组,就可以像仅包含5个元素一样传递它:
So if you have some code that expects to operate on an array of 5 chars: 因此,如果您有一些代码希望对5个字符组成的数组进行操作:
void foo(char DST1[])
{
for(int i = 0; i < 5; i++)
{
process(DST1[i]);
}
}
You can invoke it as follows: 您可以按以下方式调用它:
char ST1[]="12345";
foo(ST1);
The only difference between the definitions of ST1
and DST1
is the silent assumption that the target character set is ASCII, at least for the digits. ST1
和DST1
定义之间的唯一区别是无声假设,即至少对于数字而言,目标字符集是ASCII。
Here is another alternative: 这是另一种选择:
char CST1[5] = { '1', '2', '3', '4', '5' };
Note however that none of these char
arrays are proper C strings because they all lack a null terminator. 但是请注意,这些
char
数组都不是正确的C字符串,因为它们都缺少空终止符。 If you with to define an array that is a C string, you should use this syntax: 如果用于定义一个C字符串数组,则应使用以下语法:
char SST1[] = "12345";
Notice the missing length between the []
: the compiler will determine the length of the array from the initializer and add a null terminator, hence a length a 6
. 请注意
[]
之间缺少的长度:编译器将确定初始化程序中数组的长度,并添加一个空终止符,因此长度为6
。
C strings can be copies with strcpy
, char
arrays that do not have a null terminator should be copied with memcpy
or memmove
. C字符串可以是具有
strcpy
副本,没有空终止符的char
数组应使用memcpy
或memmove
复制。
One for all, one answer is casting. 一言以蔽之,一个答案就是铸造。 Easy way to do it:
简单的方法:
int main () {
int i;
char ST1[5]="12345";
for (i=0;i<5;i++)
printf("%d\n",(int)ST1[i]);
return 0;
}
Just like I printed, you can store it, calculate using it or anything possible. 就像我打印的一样,您可以存储它,使用它进行计算或任何可能的方法。 And as I see, you want those number in hexadecimals.
正如我所看到的,您希望这些数字以十六进制表示。 For that, just change the
printf
's placeholder with help from here - printf() formatting for hex 为此,只需在这里帮助下更改
printf
的占位符- 十六进制的printf()格式
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.