在没有(sprintf/printf 库)的情况下,在 C 中将整数转换为十六进制字符串 [英] Integer conversion to Hexadecimal String in C without (sprintf/printf libraries)

查看:33
本文介绍了在没有(sprintf/printf 库)的情况下,在 C 中将整数转换为十六进制字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这些输入变量:

 uint16 温度 = 0x1f12;uint8 数组[8] = {0,0,0,...0}

我想要

array8[0] = '1';array8[1] = 'f';数组8[2] = '1';数组8[3] = '2';array8[4] = '\0';array8[5] = '\0';array8[6] = '\0';array8[7] = '\0';

但是,对于内存问题(我正在使用微控制器!)我需要避免使用 sprintf、printf、puts 等函数.

我该怎么办?

最好的问候,

解决方案

此代码仅使用堆栈中的 8 个额外字节(int i, j).

int i;for (i = 0; i <8; i++) {数组[7 - i] = 温度 % 16;温度/= 16;如果(温度== 0)休息;}如果(我== 8)一世 - ;国际j;for (j = 0; j <= i; j++)数组[j] = 数组[7 - i + j];对于 (j = i + 1; j <8; j++)数组[j] = 0;对于 (j = 0; j <8; j++)如果(数组[j] <10)数组[j] += '0';别的数组[j] += 'a' - 10;

这段代码首先将temperature = 0x1f12 转换为array[8] = { 0, 0, 0, 0, 1, 15, 1, 2}.>

然后移动array的元素,使其成为array[8] = { 1, 15, 1, 2, 0, 0, 0, 0 }.

然后将数字转换为对应的字符:array[8] = { '1', 'f', '1', '2', '0', '0', '0', '0' }.

还要注意这个 if 条件

 if (i == 8)一世 - ;

永远不会满足,因为中断条件在第一个 for 循环中总是足够的,即使温度 >= 0x10000000.它只是在那里,希望它可以帮助某人理解此代码.

I have these input variables:

 uint16 temperature = 0x1f12;
 uint8 array[8] = {0,0,0,...0}

And I want to have

array8[0] = '1';
array8[1] = 'f';
array8[2] = '1';
array8[3] = '2';
array8[4] = '\0';
array8[5] = '\0';
array8[6] = '\0';
array8[7] = '\0';

However, for memory problems (I'm working with microcontrollers!) I need to avoid functions such as sprintf, printf, puts, etc.

How should I do?

Best regards,

解决方案

This code uses only 8 additional bytes in stack(int i, j).

int i;
for (i = 0; i < 8; i++) {
    array[7 - i] = temperature % 16;
    temperature /= 16;

    if (temperature == 0)
        break;
}

if (i == 8)
    i--;

int j;
for (j = 0; j <= i; j++)
    array[j] = array[7 - i + j];
for (j = i + 1; j < 8; j++)
    array[j] = 0;

for (j = 0; j < 8; j++)
    if (array[j] < 10)
        array[j] += '0';
    else
        array[j] += 'a' - 10;

This code first converts temperature = 0x1f12 to array[8] = { 0, 0, 0, 0, 1, 15, 1, 2}.

Then shifts the elements of array so that it becomes array[8] = { 1, 15, 1, 2, 0, 0, 0, 0 }.

And then converts the numbers to corresponding characters: array[8] = { '1', 'f', '1', '2', '0', '0', '0', '0' }.

Note also that this if condition

    if (i == 8)
        i--;

is never met, since break condition always suffices in the first for loop, even for temperature >= 0x10000000. It's just there in the hope that it might help someone understand this code.

这篇关于在没有(sprintf/printf 库)的情况下,在 C 中将整数转换为十六进制字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆