C语言 在 C 中将 int 转换为 2 字节的十六进制值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4085612/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 06:54:22  来源:igfitidea点击:

Converting an int to a 2 byte hex value in C

cstringhex

提问by MBU

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?

我需要将 int 转换为 2 字节的十六进制值以存储在 C 中的 char 数组中。我该怎么做?

回答by Vicky

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:

如果您不允许使用库函数,请手动将其划分为 nybbles:

#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] = '
int intval = /*your value*/
char hexval[5];
sprintf(hexval,"%0x",intval);
'; }

回答by slashmais

Assuming int to be 32 bits;

假设 int 为 32 位;

easiest way: just use sprintf()

最简单的方法:只需使用 sprintf()

char s[5];  // 4 chars + '
static const char hexvals[][3]= {"00", "01", "02", ... "FD", "FE", "FF"};
const char *byteStr = hexvals[number];
' int x = 4660; sprintf(s, "%04X", x);

Now use hexval[0] thru hexval[3]; if you want to use it as a null-terminated string then add hexval[4]=0;

现在使用 hexval[0] 到 hexval[3]; 如果要将其用作以空字符结尾的字符串,请添加hexval[4]=0;

回答by Denilson Sá Maia

int value = 11;

array[0] = value >> 8;
array[1] = value & 0xff;

printf("%x%x", array[0], array[1]);

You'll probably want to check sprintf()documentation. Be careful that this code is not very safe. If xis larger than 0xFFFF, the final string will have more than 4 characters and won't fit. In order to make it safer, look at snprintf().

您可能需要查看sprintf()文档。请注意,此代码不是很安全。如果x大于0xFFFF,则最终字符串将超过 4 个字符并且不适合。为了使其更安全,请查看snprintf().

回答by mikerobi

Normally I would recommend using the sprintfbased solutions recommended by others. But when I wrote a tool that had to convert billions of items to hex, sprintf was too slow. For that application I used a 256 element array, which maps bytes to strings.

通常我会建议使用sprintf其他人推荐的基于解决方案的解决方案。但是当我编写一个必须将数十亿项转换为十六进制的工具时,sprintf 太慢了。对于那个应用程序,我使用了一个 256 个元素的数组,它将字节映射到字符串。

This is an incomplete solution for converting 1 byte, don't forget to add bounds checking, and make sure the array is static or global, recreating it for every check would kill performance.

这是转换 1 字节的不完整解决方案,不要忘记添加边界检查,并确保数组是静态的或全局的,为每次检查重新创建它会降低性能。

000B

回答by MBU

Figured out a quick way that I tested out and it works.

想出了一个我测试过的快速方法,它有效。

void intToHex(int intnumber, char *txt)
{    
    unsigned char _s4='0';
    char i=4;
    //intnumber=0xffff;

    do {
        i--;
        _s4 = (unsigned char)  ((intnumber >> i*4 ) & 0x000f);
        if(_s4<10)
            _s4=_s4+48;
        else
            _s4=_s4+55;

        *txt++= _s4;    
    } while(i);     
}
...
char text [5]={0,0,0,0,0};
...

intToHex(65534,text);
USART_Write_Text(text);
....

result is:

结果是:

#include <stdio.h>

int main()
{
    char output[5];
    snprintf(output,5,"%04x",255);

    printf("%s\n",output);
    return 0;
}

which is 11 in hex.

这是 11 的十六进制。

回答by cooxee

int bar; 
// ...
char foo[sizeof(bar) * 2 + 3];
sprintf(foo, "0x%x", bar);

回答by MAK

Rather than sprintf, I would recommend using snprintfinstead.

而不是sprintf,我会建议使用snprintf

unsigned int hex16 = ((unsigned int) input_int) & 0xFFFF;

Its a lot safer, and is available in pretty much every compiler.

它更安全,并且几乎可以在每个编译器中使用。

回答by Joe Valenzuela

Most of these answers are great, there's just one thing I'd add: you can use sizeof to safely reserve the correct number of bytes. Each byte can take up to two hex digits (255 -> ff), so it's two characters per byte. In this example I add two characters for the '0x' prefix and one character for the trailing NUL.

这些答案中的大多数都很棒,我只想补充一件事:您可以使用 sizeof 来安全地保留正确的字节数。每个字节最多可以包含两个十六进制数字 (255 -> ff),因此每个字节有两个字符。在本例中,我为“0x”前缀添加了两个字符,为尾随的 NUL 添加了一个字符。

#include <stdlib.h>
#include <stdio.h>

#define BUFLEN 5

int main(int argc, char* argv[])
{
  int n, i, cn;
  char c, buf[5];
  char hexmap[17] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','.'};

  for(i=0;i<BUFLEN;i++)
    buf[i]=0;

  if(argc<2)
  {
    printf("usage: %s <int>\n", argv[0]);
    return 1;
  }
  n = atoi(argv[1]);
  i = 0;
  printf("n: %d\n", n);

  for(i=0; i<4; i++)
  {
    cn = (n>>4*i) & 0xF;
    c  = (cn>15) ? hexmap[16] : hexmap[cn];
    printf("cn: %d, c: %c\n", cn, c);

    buf[3-i] = (cn>15) ? hexmap[16] : hexmap[cn];
  }
  buf[4] = '##代码##'; // null terminate it

  printf("buf: %s\n", buf);
  return 0;
}

回答by yasouser

##代码##

input_intis the number you want to convert. hex16will have the least significant 2 bytes of input_int. If you want to print it to the console, use %xas the format specifier instead of %dand it will be printed in hex format.

input_int是您要转换的数字。hex16将具有最低有效的 2 个字节input_int。如果要将其打印到控制台,请%x用作格式说明符而不是,%d它将以十六进制格式打印。

回答by jbremnant

Here's a crude way of doing it. If we can't trust the encoding of ascii values to be consecutive, we just create a mapping of hex values in char. Probably can be optimized, tidied up, and made prettier. Also assumes we only look at capture the last 32bits == 4 hex chars.

这是一个粗略的方法。如果我们不能相信 ascii 值的编码是连续的,我们只需在 char 中创建一个十六进制值的映射。大概可以优化,整理,变得更漂亮。还假设我们只查看捕获最后 32 位 == 4 个十六进制字符。

##代码##