使用'C'程序
我想将一个数字数组转换为单个Hex值,然后转换为数组,如下所述。
输入:`unsigned char no_a [12] = {0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x01,0x02,0x03};
从上面的数组形成的单个数字是123456789123.
it's hex equivalent is
0x1CBE991A83`。
期待输出:unsigned char no_b[5] = {0x1C,0xBE,0x99,0x1A,0x83};
我已经通过在长64bit(8byte)变量中创建单个数字(123456789123)来实现此逻辑。但现在我有一个限制,没有64位变量这样做。任何人都有任何想法实现这个........?
感谢....
答案 0 :(得分:0)
你可以使用'long arithmetic'来解决这个问题:用数字数组表示整数。
转换为base-16只需要实现除法运算。
答案 1 :(得分:0)
#include <stdio.h>
#include <stdlib.h>
int cmp(int a[2], int b[2]){
if(a[0]>b[0]) return 1;
if(a[0]<b[0]) return -1;
return a[1] - b[1];
}
void sub(int a[2], int b[2], int *q, int *r){//be improved
// a / b = q...r
int borrow;
for(*q=0;cmp(a,b) > 0;++*q){
borrow = 0;
a[1] -= b[1];
if(a[1]<0){
borrow = 1;
a[1]+=1000000;
}
a[0] -= b[0] + borrow;
}
*r = a[0]*1000000 + a[1];
}
unsigned char no_b[8];
int pos = 0;
void convert(int x){
div_t qr;
if(x < 256){
no_b[pos++] = x;
return;
}
if(x >= 65536){
qr = div(x, 65536);
convert(qr.quot);
convert(qr.rem);
return;
}
if(x >= 256){
qr = div(x, 256);
convert(qr.quot);
convert(qr.rem);
}
}
int main(void){
int a[2] = { 123456,789123 }; // base 1000000
int b3[2] = { 16, 777216 };//256^3 base 1000000
int q,r,i;
sub(a, b3, &q, &r);
convert(q);
convert(r);
for(i=0;i<pos;++i)
printf("%02X", no_b[i]);//1CBE991A83
return 0;
}
答案 2 :(得分:0)
Thanks to all for your answers. Below is the simple logic i implemented....
void DecToHex(unsigned char* dst, unsigned char* src);
unsigned char digits[12] = {0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x01,0x02,0x03};
unsigned char result[10]= {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
void main(void)
{
/* digits[12] = {0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x01,0x02,0x03}; */
DecToHex(result, digits);
/* result[10] : 0x1C,0xBE,0x99,0x1A,0x83,......... */
while(1);
}
void DecToHex(unsigned char* dst, unsigned char* src)
{
unsigned char tmp;
unsigned char i, j=10;
while(j!=0)
{
j -= 1;
/* reinitialize for every division */
tmp = 0;
for(i=9-j;i<12;i++){
tmp = (tmp*10)+src[i];
if(tmp < 16){
src[i] = 0x00;
}
else{
src[i] = tmp/16;
tmp = tmp%16;
}
}
/* last tmp is the reminder of first division */
dst[j] = tmp;
}
/* for hex array */
for(i=0,j=0;i<12;i+=2, j+=1){
dst[j] = (unsigned char)((dst[i] << 4)|(dst[i+1]));
}
}