kraisyth
kraisyth

Reputation: 13

How can I convert an integer to a hex byte stored in a char array?

I'm currently working on storing an integer, that will fit in one hex byte, as a hex value in a character array. For instance my input would be something like:

int i = 28;

And the output would be something like:

char hex[1] = {'\x1C'};

What's the easiest way to do this?

Upvotes: 0

Views: 2746

Answers (2)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385325

char hex[1] = {i};

That's it.

To avoid warnings about narrowing conversions, you could cast to char too.

There is no such thing as a "hex byte"; only a byte. It's only "hex" when you wrote it as a literal in your source code. Like every other value, it is not stored on your computer in hex or in decimal, but in binary.

So, the base is irrelevant. You already have the value. Just put it in the array.

Upvotes: 3

BlooB
BlooB

Reputation: 965

This Way Use std::stringstream to convert integers into strings and its special manipulators to set the base. For example like that:

std::stringstream sstream;
sstream << std::hex << my_integer;
std::string result = sstream.str();

OR

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();
}

Upvotes: -1

Related Questions