Integer to Hex String in C++

Integer conversion to Hexadecimal String in C without (sprintf/printf libraries)

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.

How to convert string to hex value in C

The question

"How can I convert a string to a hex value?"

is often asked, but it's not quite the right question. Better would be

"How can I convert a hex string to an integer value?"

The reason is, an integer (or char or long) value is stored in binary fashion in the computer.

"6A" = 01101010

It is only in human representation (in a character string) that a value is expressed in one notation or another

"01101010b"   binary
"0x6A" hexadecimal
"106" decimal
"'j'" character

all represent the same value in different ways.

But in answer to the question, how to convert a hex string to an int

char hex[] = "6A";                          // here is the hex string
int num = (int)strtol(hex, NULL, 16); // number base 16
printf("%c\n", num); // print it as a char
printf("%d\n", num); // print it as decimal
printf("%X\n", num); // print it back as hex

Output:

j
106
6A

How to convert from char * to int to hex decimal in C

This is wrong:

char out[2];
sprintf(out, "%x", num); // to hex

because you write beyond the bounds of the array. Your number has two hexadecimal places, and you need an additional byte for the \0 terminator of the string. It has to be at least char out[3].

This is even wronger:

for(int i=0;i<2;i++)
printf("%x\n", out[i]);

You already have a hexadecimal string representation of the number and now take the individual characters and interpret them as hexadecimal numbers. Just output your out string instead, e.g. puts(out) or printf("%s\n", out) (requires the \0 terminator to be present).

You can condense the whole thing to just

int main(void)
{
char *input = "78";
long num = strtol(input, NULL, 10); // to int
printf("%lx\n", num); // to hex
}

(note that strtol() returns long -- with larger numbers you'd get a problem converting this to int.)

Converting an int to a 2 byte hex value in C

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';
}

Integer to hex string in C++

Use <iomanip>'s std::hex. If you print, just send it to std::cout, if not, then use std::stringstream

std::stringstream stream;
stream << std::hex << your_int;
std::string result( stream.str() );

You can prepend the first << with << "0x" or whatever you like if you wish.

Other manips of interest are std::oct (octal) and std::dec (back to decimal).

One problem you may encounter is the fact that this produces the exact amount of digits needed to represent it. You may use setfill and setw this to circumvent the problem:

stream << std::setfill ('0') << std::setw(sizeof(your_type)*2) 
<< std::hex << your_int;

So finally, I'd suggest such a function:

template< typename T >
std::string int_to_hex( T i )
{
std::stringstream stream;
stream << "0x"
<< std::setfill ('0') << std::setw(sizeof(T)*2)
<< std::hex << i;
return stream.str();
}

How to convert a gi-normous integer (in string format) to hex format? (C#)

Oh, that's easy:

        var s = "843370923007003347112437570992242323";
var result = new List<byte>();
result.Add( 0 );
foreach ( char c in s )
{
int val = (int)( c - '0' );
for ( int i = 0 ; i < result.Count ; i++ )
{
int digit = result[i] * 10 + val;
result[i] = (byte)( digit & 0x0F );
val = digit >> 4;
}
if ( val != 0 )
result.Add( (byte)val );
}

var hex = "";
foreach ( byte b in result )
hex = "0123456789ABCDEF"[ b ] + hex;


Related Topics



Leave a reply



Submit