[英]C - Converting hex into char array
I have an unit32_t
in hex format: uint32_t a = 0xdddddddd
how can I convert it into an我有一个十六进制格式的
unit32_t
: uint32_t a = 0xdddddddd
我如何将它转换成一个
array[8] = {0,x,d,d,d,d,d,d,d,d}
I tried to use:我尝试使用:
for(int i = 0; i < 8; i++){
array[i] = (a & (0x80 >> i)) > 0;
}
if you are referring to using the array to store every hex digit in a place in the array then you can do:如果您指的是使用数组将每个十六进制数字存储在数组中的某个位置,那么您可以执行以下操作:
for(int i = 0; i < 8; i++){
array[i] = a & 0x0F;
a = a >> 4;
}
where every time, we get the right most hex digit (which is 4 bits) and assign that to the array and then we shift left a
to get the next right most 4 bits as every hex digit is 4 bits indeed.每次,我们都得到最右边的十六进制数字(4 位)并将其分配给数组,然后我们向左移动
a
以获得下一个最右边的 4 位,因为每个十六进制数字确实是 4 位。
but if you are referring to converting that hex number into a string then you can use the function called itoa
with the base = 16 .但是如果您指的是将该十六进制数转换为字符串,那么您可以使用名为
itoa
的 function 和base = 16 。 but notice that itoa()
is not a C
standard function. It is a non-standard extension provided by a specific implementation.但请注意
itoa()
不是C
标准 function。它是特定实现提供的非标准扩展。
so you can write:所以你可以写:
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
int main(void)
{
uint32_t a = 0xdddddddd;
char array[10];
itoa(a, array, 16);
printf("array = 0x%s\n", array);
return 0;
}
and this is the output:这是 output:
array = 0xdddddddd
Another conforming implementation can simply use snprintf()
as intended to write the representation of the number in a
in hex to array
.另一个符合要求的实现可以简单地使用
snprintf()
来将十六进制数字a
表示形式写入array
。 In that case, all that is needed is a sufficiently sized array
and:在这种情况下,所需要的只是一个足够大的
array
和:
snprintf (array, sizeof array, "%x", a);
See: man 3 printf and C18 Standard - 7.21.6.5 The snprintf function请参阅: man 3 printf和C18 标准 - 7.21.6.5 snprintf function
A short example outputting each element of array
after filling with a
would be:在用
a
填充后输出array
的每个元素的一个简短示例是:
#include <stdio.h>
#include <stdint.h>
int main (void) {
char array[16] = "";
uint32_t a = 0xdddddddd;
/* write a to array in hex validatating array was of sufficient size */
if ((size_t)snprintf (array, sizeof array, "%x", a) >= sizeof array)
fputs ("warning: representation of 'a' truncated.\n", stderr);
/* output results */
for (int i = 0; array[i]; i++)
printf ("array[%2d] : '%c'\n", i, array[i]);
}
Example Use/Output示例使用/输出
$ ./bin/hex2char
array[ 0] : 'd'
array[ 1] : 'd'
array[ 2] : 'd'
array[ 3] : 'd'
array[ 4] : 'd'
array[ 5] : 'd'
array[ 6] : 'd'
array[ 7] : 'd'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.