转换一个C十六进制值到一个char * [英] Convert a c hex value into a char*

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

问题描述

如何在C 十六进制值转换成等价的的char * 值。例如,如果十六进制值 1df2 中的char *还应该包含 1df2

How to convert a hex value in c into an equivalent char* value. For example if the hex value is 1df2 the char* should also contain 1df2.

我现在用的是 VINC 编译器,为 VNC2 USB芯片的 VINL 链接 FTDI 。它有以下这些头文件; STDLIB STDIO 字符串。这些不过是主要的C库的子集,并且没有明显的答案,如的snprintf 的sprintf

I am using the VinC compiler and the VinL linker for the VNC2 USB Chip from FTDI. It has these following header files; stdlib, stdio and string. These are however subsets of the main c libraries and don't have the obvious answers such as snprintf or sprintf.

文档说以下类型是有效的,

The docs say the following types are valid,

有它在整个内核和驱动程序用于变量和函数类型的某些定义。它们可在 vos.h 头文件的应用程序。

There are certain definitions for variable and function types which are used throughout the kernel and drivers. They are available to applications in the vos.h header file.

空指针和逻辑定义:

#define NULL                0
#define TRUE                1
#define FALSE               0

变量类型定义:

#define uint8               unsigned char
#define int8                char
#define int16               short
#define uint16              unsigned short
#define uint32              unsigned int
#define pvoid               unsigned char *

功能类型定义:

typedef uint8 (*PF)(uint8);
typedef void (*PF_OPEN)(void *);
typedef void (*PF_CLOSE)(void *);
typedef uint8 (*PF_IOCTL)(pvoid);
typedef uint8 (*PF_IO)(uint8 *, unsigned short, unsigned short *);
typedef void (*PF_INT)(void);

有什么建议?

推荐答案

使用的snprintf()

int to_hex(char *output, size_t len, unsigned n)
{    
    return snprintf(output, len, "%.4x", n);
}


鉴于新的信息这是一个相当基本的嵌入式系统,那么如果你只是对16位数字感兴趣这样一个最小的解决方案可能足以


Given the new information that it's a fairly basic embedded system, then if you're only interested in 16 bit numbers a minimal solution like this probably suffices:

/* output points to buffer of at least 5 chars */
void to_hex_16(char *output, unsigned n)
{
    static const char hex_digits[] = "0123456789abcdef";

    output[0] = hex_digits[(n >> 12) & 0xf];
    output[1] = hex_digits[(n >> 8) & 0xf];
    output[2] = hex_digits[(n >> 4) & 0xf];
    output[3] = hex_digits[n & 0xf];
    output[4] = '\0';
}

(应该清楚如何把它扩展到更广泛的数字)。

(It should be clear how to extend it to wider numbers).

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

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