Converting an int to a 2 byte hex value in C
I need to convert an int to a 2 byte hex value to store in a c开发者_StackOverflowhar 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';
}
Figured out a quick way that I tested out and it works.
int value = 11;
array[0] = value >> 8;
array[1] = value & 0xff;
printf("%x%x", array[0], array[1]);
result is:
000B
which is 11 in hex.
Assuming int to be 32 bits;
easiest way: just use sprintf()
int intval = /*your value*/
char hexval[5];
sprintf(hexval,"%0x",intval);
Now use hexval[0] thru hexval[3]; if you want to use it as a null-terminated string then add hexval[4]=0;
char s[5]; // 4 chars + '\0'
int x = 4660;
sprintf(s, "%04X", x);
You'll probably want to check sprintf()
documentation. Be careful that this code is not very safe. If x
is 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()
.
Normally I would recommend using the sprintf
based 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.
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.
static const char hexvals[][3]= {"00", "01", "02", ... "FD", "FE", "FF"};
const char *byteStr = hexvals[number];
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);
....
Rather than sprintf
, I would recommend using snprintf
instead.
#include <stdio.h>
int main()
{
char output[5];
snprintf(output,5,"%04x",255);
printf("%s\n",output);
return 0;
}
Its a lot safer, and is available in pretty much every compiler.
Perhaps try something like this:
void IntToHex(int value, char* buffer) {
int a = value&16;
int b = (value>>4)&16;
buffer[0] = (a<10)?'0'+a:'A'-(a-10);
buffer[1] = (b<10)?'0'+b:'A'-(b-10);
}
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.
int bar;
// ...
char foo[sizeof(bar) * 2 + 3];
sprintf(foo, "0x%x", bar);
unsigned int hex16 = ((unsigned int) input_int) & 0xFFFF;
input_int
is the number you want to convert. hex16
will have the least significant 2 bytes of input_int
. If you want to print it to the console, use %x
as the format specifier instead of %d
and it will be printed in hex format.
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.
#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] = '\0'; // null terminate it
printf("buf: %s\n", buf);
return 0;
}
This function works like a charm.
void WORD2WBYTE(BYTE WBYTE[2], WORD Value) {
BYTE tmpByte[2];
// Converts a value from word to word byte ----
memcpy(tmpByte, (BYTE*) & Value, 2);
WBYTE[1] = tmpByte[0];
WBYTE[0] = tmpByte[1];
}
asumming the following:
typedef unsigned char BYTE;
typedef unsigned short WORD;
Example of use:
we want to achieve this:
integer = 92
byte array in hex:
a[0] = 0x00;
a[1] = 0x5c;
unsigned char _byteHex[2];
WORD2WBYTE(_byteHex, 92);
you can use this it is simple and easy to convert
typedef union {
struct hex{
unsigned char a;
unsigned char b;
}hex_da;
short int dec_val;
}hex2dec;
hex2dec value;
value.dec_val=10;
Now hex value is stored in hex_da structure access it for further use.
Using Vicky's answer above
typedef unsigned long ulong;
typedef unsigned char uchar;
#define TO_HEX(i) (i <= 9 ? '0' + i : 'A' - 10 + i)
#define max_strhex (sizeof(ulong)*2)
public uchar
*mStrhex(uchar *p, ulong w, ulong n)
{
ulong i = 0xF; // index
ulong mask = i << (((sizeof(ulong)*2)-1)*4); // max mask (32 bit ulong mask = 0xF0000000, 16 bit ulong mask = 0xF000)
ulong shift = (w*4); // set up shift to isolate the highest nibble
if(!w || w > max_strhex) // no bold params
return p; // do nothing for the rebel
mask = mask >> (max_strhex-w)*4; // setup mask to extract hex nibbles
for(i = 0; i < w; i++){ // loop and add w nibbles
shift = shift - 4; // hint: start mask for four bit hex is 0xF000, shift is 32, mask >> 32 is 0x0000, mask >> 28 is 0x000F.
*p++ = TO_HEX(((n & mask) >> shift)); // isolate digit and make hex
mask = mask >> 4; //
*p = '\0'; // be nice to silly people
} //
return p; // point to null, allow concatenation
}
For dynamic fixed length of hex
string makeFixedLengthHex(const int i, const int length)
{
std::ostringstream ostr;
std::stringstream stream;
stream << std::hex << i;
ostr << std::setfill('0') << std::setw(length) << stream.str();
return ostr.str();
}
But negative you have to handle it yourself.
精彩评论