转换一个int在C 2字节十六进制值 [英] Converting an int to a 2 byte hex value in C

查看:367
本文介绍了转换一个int在C 2字节十六进制值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个int转换为2个字节十六进制值在字符数组存储,在C.我怎么能这样做呢?

I need to convert an int to a 2 byte hex value to store in a char array, in C. How can I do this?

推荐答案

如果你被允许使用的库函数:

If you're allowed to use library functions:

int x = SOME_INTEGER;
char res[5]; /* two bytes of hex = 4 characters, plus NULL terminator */

if (x <= 0xFFFF)
{
    sprintf(&res[0], "%04x", x);
}

您整数可能包含四个以上的十六进制数字价值的数据,因此首先检查。

Your integer may contain more than four hex digits worth of data, hence the check first.

如果你不允许使用库函数,把它分解成手动半字节:

If you're not allowed to use library functions, divide it down into nybbles manually:

#define TO_HEX(i) (i <= 9 ? '0' + i : 'A' - 10 + i)

int x = SOME_INTEGER;
char res[5];

if (x <= 0xFFFF)
{
    res[0] = TO_HEX(((x & 0xF000) >> 12));   
    res[1] = TO_HEX(((x & 0x0F00) >> 8));
    res[2] = TO_HEX(((x & 0x00F0) >> 4));
    res[3] = TO_HEX((x & 0x000F));
    res[4] = '\0';
}

这篇关于转换一个int在C 2字节十六进制值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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