Reputation: 476
I have a char array of hex values and would like to convert them into a single integer value. I have two issues with the code I am currently using:
Problem 1: the value stored in strHex after running this is - "0927ffffffc0" when I want it to be "000927C0" - what is the reason for the extra "ffffff" being added?
Problem 2: I would like a solution to convert a char array of hex values to an integer without using stringstream if possible.
char cArray[4] = { 0x00, 0x09, 0x27, 0xC0 }; // (600000 in decimal)
std::stringstream ss;
for (int i = 0; i < 4; ++i)
{
ss << std::hex << (int)cArray[i];
}
std::string strHex = ss.str();
int nHexNumber;
sscanf(strHex.c_str(), "%x", &nHexNumber);
nHexNumber should be 600000 when converted and its giving me -64.
Upvotes: 1
Views: 2701
Reputation: 8406
#include <stdint.h>
#include <iostream>
int main(int argc, char *argv[]) {
unsigned char cArray[4] = { 0x00, 0x09, 0x27, 0xC0 };
uint32_t nHexNumber = (cArray[0] << 24) | (cArray[1] << 16) | (cArray[2] << 8) | (cArray[3]);
std::cout << std::hex << nHexNumber << std::endl;
return 0;
}
Edited: As pointed out by M.M this is not depending on endianness as originally stated.
Output under QEMU:
user@debian-powerpc:~$ uname -a
Linux debian-powerpc 3.2.0-4-powerpc #1 Debian 3.2.51-1 ppc GNU/Linux
user@debian-powerpc:~$ ./a.out
927c0
user@debian-powerpc:~$
Under Ubuntu on Windows:
leus@owl:~$ uname -a
Linux owl 4.4.0-43-Microsoft #1-Microsoft Wed Dec 31 14:42:53 PST 2014 x86_64 x86_64 x86_64 GNU/Linux
leus@owl:~$ ./a.out
927c0
leus@owl:~$
Upvotes: 3
Reputation: 981
#include<arpa/inet.h>
#include<iostream>
using namespace std;
union {
unsigned char cA[4] = { 0x00, 0x09, 0x27, 0xc0 };
int k;
} u;
int main()
{
cout << htonl(u.k) << endl;
}
simple way is to use htonl...
Upvotes: 0