[英]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: 我有一个int数组,代表一个非常大的数字,如:
// ...
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: 所以这是我对这个问题的看法:
To build this unsigned long long, assuming an array of DECIMAL digits: 要构建这个无符号长long,假设有一个DECIMAL数字数组:
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: 要构建这个无符号长long,假设一个十六进制数字数组:
for (int i=0; i < n1.length ; i++ ){
myNum += pow(16,i)* n1[n1.length - i];
}
(Notice the base 16) (注意基数16)
Disclaimer: limited to exactly 16 digits MAX stored in your array. 免责声明:限制在阵列中存储的16位MAX。 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). 好吧,int是一个int是一个int ...(在内存中)。
There are 10 fingers on my hands whether or not I call that number 10, or A. 我的手上有10个手指,无论我是否拨打该号码10或A.
If you want to format the number for DISPLAY in hex, then try something like: 如果要格式化十六进制的DISPLAY数字,请尝试以下操作:
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. 您可以使用GMP库使这一点相对简单。
basic_stringstream<unsigned int>
to wrap your array. basic_stringstream<unsigned int>
来包装数组。 operator <<
to read it into a mpz_t
variable. operator <<
将其读入mpz_t
变量。 basic_stringstream<unsigned int>
for your result. basic_stringstream<unsigned int>
。 std::hex
and operator >>
to write the variable back out in hexadecimal. std::hex
和operator >>
以std::hex
形式写回变量。 That would work on ASCII digits, but yours aren't. 这将适用于ASCII数字,但你的不是。 You can still use GMP, but you'll want to use the
mpn_get_str
and mpn_set_str
functions instead. 您仍然可以使用GMP,但您需要使用
mpn_get_str
和mpn_set_str
函数。 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. 您需要将您的数字复制到
unsigned char[]
,然后您可以指定转换为mp_limb_t
并返回到一串数字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.