How can to convert hexadecimal to string? C++ - c++

I have an array of hexadecimals and I need to convert it to string.
my array:
// declaration
unsigned char HEX_bufferMessage[12];
// initialize
HEX_bufferMessage[0] = 0xF0;
HEX_bufferMessage[1] = 0x15;
HEX_bufferMessage[2] = 0x31;
HEX_bufferMessage[3] = 0x02;
HEX_bufferMessage[4] = 0x03;
HEX_bufferMessage[5] = 0x00;
HEX_bufferMessage[6] = 0x00;
HEX_bufferMessage[7] = 0xD1;
HEX_bufferMessage[8] = 0xD1;
HEX_bufferMessage[9] = 0x00;
HEX_bufferMessage[10] = 0x00;
HEX_bufferMessage[11] = 0xF7;
I only have these informations in hexadecimal format, I need to convert them to string. Anyone know how I can do it??
Thank you!!

Late to the party, but since all the answers using std::to_string() fail to output the hex values as hex values, I suggest you send them to a stream, where you can format your output via std::hex:
std::cout << "0x" << std::hex << HEX_bufferMessage[0] << std::endl;
or, if you want to use it in a string:
std::string to_hex_string( const unsigned int i ) {
std::stringstream s;
s << "0x" << std::hex << i;
return s.str();
}
or even in a single line:
// ...
return (static_cast<std::stringstream const&>(std::stringstream() << "0x" << std::hex << i)).str();

std::bitset<16> foo(HEX_bufferMessage[0]);
std::string s = foo.to_string();
http://en.cppreference.com/w/cpp/utility/bitset/to_string

Use : std::to_string
for (size_t i =0 ; i<10; ++i)
{
std::string s { std::to_string(HEX_bufferMessage[i]) }; //ith element
std::cout << s; //concatenate all s as per need
}

something like this?
const char *hex = "0123456789ABCDEF";
unsigned char x = 0xF8;
std::cout << "0x" << hex[x >> 4 & 0xF] << hex[x & 0xF] << std::endl;

How about std::to_string?
Like
std::string s;
for (auto const& v : HEX_bufferMessage)
s += std::to_string(v);

char hex_string[12*2+1]; /* where 12 - is the number of you hex values, 2 - is 2 chars per each hex, and 1 is the final zero character */
for(int i=0;i<12;++i) {
sprintf(hex_string+i*2,"%x", HEX_bufferMessage[i]);
}

Related

int To String Representation of Fixed Length

I have a function that accepts a few integer params, and needs to convert then to ASCII string representation of a fixed length of 4. i.e. 4 becomes "0004" and 42 becomes "0042". It is safe to assume the params will be 0<=n<=9999
I could do that with something like:
void foo(int a, int b) {
std::string sa = std::to_string(a);
std::string sb = std::to_string(b);
for(int i = sa.length; i < 4; i++)
sa.insert(0,"0");
...
}
But that seems like more than I should need, especially if there are a lot of params to convert. is there a more efficient way to do this?
Edit: the goal is not to print the resulting strings.
Edit 2: something based around ss << std::setw( 4 ) << std::setfill( '0' ) << number; does what I need, thank you for the comments.
You can use std::ostringstream and treat it like an output stream:
std::ostringstream ss;
ss << std::setw( 4 ) << std::setfill( '0' ) << number;
Send_To_Serial(ss.str().c_str());
I think snprintf is a good candidate:
#include <cstdio>
#include <iostream>
int main() {
char buffer[5];
// Prints: 0001
snprintf(buffer, 5, "%04d", 1);
std::cout << buffer << '\n';
// Prints: 1234 (not the 5)
snprintf(buffer, 5, "%04d", 12345);
std::cout << buffer << '\n';
}

int to Hex string (C++)

I have done some research on how to convert an int to Hex string and found an answer, however what i need is a little bit different as you can see in the following code:
int addr = 5386; //
std::string buffer = "contains 0xCCCCCCCC as hex (non ASCII in the string)";
size_t idx = 0;
idx = buffer.find("\xCC\xCC\xCC\xCC", idx);
if (idx != string::npos) buffer.replace(idx, 4, XXX); // here i want to put the addr variable but as 0x0000150A
What i need is a way to convert the addr variable to a hex string that has the \x in between the bytes like "\x0a\x15\x00\x00"
Thanks in advance.
Maybe this program would help you :
#include <sstream>
#include <iomanip>
#include <iostream>
int main(int argc, char const *argv[])
{
int a = 5386;
std::ostringstream vStream;
for(std::size_t i = 0 ; i < 4 ; ++i)
vStream << "\\x"
<< std::right << std::setfill('0') << std::setw(2) << std::hex
<< ((a >> i*4) & 0xFF);
std::cout << vStream.str() << std::endl;
return 0;
}
I am not sure I precisely got your problem, but I understand you want an int to be transformed into a string in format : "\xAA\xAA\xAA\xAA".
It uses std::right, std::setfill('0') and std::setw(2) to force an output of "2" to be "02". std::hex is to get the hexadecimal representation of a integer.
You may want to treat addr as char*, but you will have issues with endianness.
you may do the job manually with something like:
unsigned int addr = 5386 // 0x0000150A
char addrAsHex[5] = {(addr >> 24) & 0xFF, (addr >> 16) & 0xFF, (addr >> 8) & 0xFF, addr & 0xFF, 0};
// ...
buffer.replace(idx, 4, addrAsHex);
Something like this:
char buf[20];
uint32_t val;
sprintf(buf, "\\x%02x\\x%02x\\x%02x\\x%02x",
(val >> 24), (uint8_t)(val >> 16), (uint8_t)(val >> 8), (uint8_t)val);

Convert unsigned char* array to std::string

I'm using this code to convert the unsigned char* (points to an array of 256 values) to std::string:
int ClassA::Func(unsigned char *dataToSend, int sendLength)
{
std::stringstream convertStream;
std::string dataToSendStr = "";
for(int i=0; i<=sendLength; i++) convertStream << dataToSend[i];
while(!convertStream.eof()) convertStream >> dataToSendStr;
...
}
but then I have dataToSendStr in this format:
dataToSendStr ""
[0] 0x00
[1] 0x00
[2] 0x04
[3] 0xC0
if I now use this value I only get "" and not the important values [0-3]!
-> need something like: dataToSendStr "000004C0"
Thx for your help!
Use the IO manipulator std::hex if you want (which is what I think based on the need something like part of the question) a hexadecimal representation of the characters in dataToSend:
std::ostringstream convertStream;
convertStream << std::hex << std::setfill('0');
for (int i = 0; i < sendLength; i++)
{
convertStream << std::setw(2) << static_cast<short>(dataToSend[i]);
}

How to convert fom string to hexadecimal?

I have the following string: s="80". I need to put this in an
unsigned char k[]. The unsigned char should look like this: unsigned char k[]={0x38,0x34}, where 0x38=8 and 0x34=0 These are the hexadecimal values for 8 and 0. How to do this? Need some help!
Please give some code. Thx
I am working on ubuntu c++ code. THX!
I use this for an encryption! I need 0x38 in an unsigned char.PLEASE HELP! Need some code:)
EDIT:
HOW TO OBTAIN THE DEC/CHAR VALUE AND PUT IT IN AN unsigned char k[]?
I've realised that it's ok if in the unsigned char [] i have the dec values {56,52} of the 8 and 0 that i have in the string!
Assuming you want this string converted as ASCII (or UTF-8) it is already in the correct format.
std::string s="80";
std::cout << "0x" << std::hex << static_cast<int>(s[0]) << "\n";
std::cout << "0x" << std::hex << static_cast<int>(s[1]) << "\n";
If you want it in an int array, then just copy it:
int data[2];
std::copy(s.begin(), s.end(), data);
I think that no matter you store '8' or 0x39, they will be present as the same binary numbers by the computer.
I think you do not really understand what you are asking.
The following are synonyms:
std::string s = "\x38\x30";
std::string s = "80";
As the following are synonyms:
char c = '8', s = '0' ;
char c = s[0], s = s[1];
char c = 0x38, s = 0x30;
It is exactly the same (except if your base encoding is not ASCII). This is not an encryption.
std::string s = "80";
unsigned char * pArray = new unsigned char[ s.size() ];
const char * p = s.c_str();
unsigned char * p2 = pArray;
while( *p )
*p2++ = *p++;
delete []pArray;
You can try it. I did not write these codes. I found I like you
#include <algorithm>
#include <sstream>
#include <iostream>
#include <iterator>
#include <iomanip>
namespace {
const std::string test="mahmutefe";
}
int main() {
std::ostringstream result;
result << std::setw(2) << std::setfill('0') << std::hex << std::uppercase;
std::copy(test.begin(), test.end(), std::ostream_iterator<unsigned int>(result, " "));
std::cout << test << ":" << result.str() << std::endl;
system("PAUSE");
}
convert that string to a char array, then subrtact '0' from each char.

How to convert ASCII string to hexadecimal?

I have tried to find this topic on the web but I couldn't find the one I need.
I have a string of character:
char * tempBuf = "qj";
The result I want is 0x716A, and that value is going to be converted into decimal value.
Is there any function in vc++ that can be used for that?
You can use a stringstream to convert each character to a hexadecimal representation.
#include <iostream>
#include <sstream>
#include <cstring>
int main()
{
const char* tempBuf = "qj";
std::stringstream ss;
const char* it = tempBuf;
const char* end = tempBuf + std::strlen(tempBuf);
for (; it != end; ++it)
ss << std::hex << unsigned(*it);
unsigned result;
ss >> result;
std::cout << "Hex value: " << std::hex << result << std::endl;
std::cout << "Decimal value: " << std::dec << result << std::endl;
}
So if I understood correctly the idea...
#include <stdint.h>
uint32_t charToUInt32(const char* src) {
uint32_t ret = 0;
char* dst = (char*)&ret;
for(int i = 0; (i < 4) && (*src); ++i, ++src)
dst[i] = *src;
return ret;
}
If I understand what you want correctly: just loop over the characters, start to finish; at each character, multiply the sum so far by 256, and add the value of the next character; that gives the decimal value in one shot.
What you are looking for is called "hex encoding". There are a lot of libraries out there that can do that (unless what you were looking for was how to implement one yourself).
One example is crypto++.