简体   繁体   中英

How to convert a char array of hex values to a single integer value in c++?

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.

#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 MM 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:~$
#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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM