简体   繁体   中英

how do I convert an integer which is defined in an int array to hex?

I have an int array that represents a very large number such as:

// ...
unsigned int n1[200];
// ...

n1 = {1,3,4,6,1,...} ==> means my number is 13461...

How can I convert that large number to its hex value?

So here is my take on the problem:

  1. You have an array of digits.
  2. You want to build an unsigned int from this array of digits.
  3. The array of digits could be either HEX digits, or DECIMAL digits.

To build this unsigned long long, assuming an array of DECIMAL digits:

unsigned long long myNum = 0;
unsigned int n1[200];

for (int i=0; i < n1.length ; i++ ){
    myNum += pow(10,i) * n1[n1.length - i];
}

To build this unsigned long long, assuming an array of HEX digits:

for (int i=0; i < n1.length ; i++ ){
    myNum += pow(16,i)* n1[n1.length - i];
}

(Notice the base 16)

Disclaimer: limited to exactly 16 digits MAX stored in your array. After that you will overrun the buffer

If it is just a matter of DISLAYING the number in the correct format...

Well, an int is an int is an int... (in memory).

There are 10 fingers on my hands whether or not I call that number 10, or A.

If you want to format the number for DISPLAY in hex, then try something like:

unsigned int i = 10;
//OR
unsigned int i = 0xA;

printf("My number in hex: %x", i);
printf("My number in decimal: %d", i);

I'm unsure if you want the hexadecimal represented as a string. If that's the case, here's some code:

#include <iostream>
#include <stack>
using namespace std;

string toHexa(int num){
    string digit = "0123456789ABCDEF", numStr = "";
    stack<char> s;

    do {
        s.push(digit[num%16]);
        num /= 16;
    } while (num != 0);

    while (!s.empty()){
        numStr += s.top();
        s.pop();
    }
    return numStr;
}

int main(){
    int num = 235; // EB in hexa
    cout << num << " to hexadecimal: " << toHexa(num) << endl;
    return 0;
}

You could use the GMP library to make this relatively straightforward.

\n
  • Use basic_stringstream<unsigned int> to wrap your array.
  • Use operator << to read it into a mpz_t variable.
  • Create another basic_stringstream<unsigned int> for your result.
  • Use std::hex and operator >> to write the variable back out in hexadecimal.

That would work on ASCII digits, but yours aren't. You can still use GMP, but you'll want to use the mpn_get_str and mpn_set_str functions instead. You'll need to copy your digits into an unsigned char[] and then you can specify the base for conversion to mp_limb_t and back to a string of digits.

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