0

使用“C”程序

我想将一个数字数组转换为单个十六进制值,然后转换为一个数组,如下所述。

输入:`unsigned char no_a[12] = {0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x01,0x02,0x03};

由上述数组形成的单个数字是123456789123. it's hex equivalent is0x1CBE991A83`。

期待输出:unsigned char no_b[5] = {0x1C,0xBE,0x99,0x1A,0x83};

我已经通过在一个 long long 64bit(8byte) 变量中创建一个数字(123456789123) 来实现这个逻辑。但现在我有一个限制,在没有 64 位变量的情况下这样做。任何人有任何想法来实现这个............?

谢谢....

4

3 回答 3

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;
}
于 2013-05-09T16:24:00.967 回答
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]));
  }
}
于 2013-05-13T05:02:47.970 回答
0

您可以使用“长算术”来解决这个问题:用数字数组表示整数。

转换为 base-16 只需要执行除法运算。

于 2013-05-09T14:37:12.267 回答