簡體   English   中英

將數字數組轉換為c中的單個十六進制值

[英]Convert array of numbers into single Hex value in c

使用“ C”程序

我想將數字數組轉換為單個十六進制值,然后轉換為如下所述的數組。

輸入:`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位變量就不能這樣做。 任何人有實現此目標的任何想法.....?

謝謝....

您可以使用“長運算”來解決此問題:用數字數組表示整數。

轉換為base-16只需執行除法運算。

#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;
}
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]));
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM