簡體   English   中英

將十進制數組(str)轉換為二進制數組(bytes)

[英]convert decimal array(str) to binary array(bytes)

請提供一些代碼,將c的大整數值的十進制值的char []數組轉換為bytes數組。

如何將下面的代碼轉換為大的十進制值數組,例如將結果作為長字節數組獲取?

static int dec2bin (char inbuf[], int num_convert)
{
  char ctemp;
  int result, power;

  num_convert--; /* index of LS char to convert */
  result = 0;
  power = 1;
  while (num_convert >= 0)
  {
    ctemp = inbuf[num_convert--]; /* working digit */
    if (isdigit(ctemp))
    {
      result += ((ctemp-'0') * power);
      power *= 10;
    }
    else
      return(0); /* error: non-numeric digit detected */
  }
  return (result);
}

不,它不僅僅是long值,它實際上是biginteger值,任何人都可以將dec轉換為字節(二進制轉換邏輯,我將用我的bigint實現和bigint運算符(add,mult)等替換int,

塞繆爾是對的!

提前致謝。

例如我可以替換以下內容

static int dec2bin (char inbuf[], bigint num_convert) 
{ 
  char ctemp; 
  bigint result, power; 

  num_convert--; /* index of LS char to convert */ 
  result = 0; 
  power = 1; 
  while (num_convert >= 0) 
  { 
    ctemp = inbuf[num_convert--]; /* working digit */ 
    if (isdigit(ctemp)) 
    { 
      result = bi_add(result ,(bi_mult((ctemp-'0'), power)); 
      power = bi_mult(power , 10); 
    } 
    else 
      return(0); /* error: non-numeric digit detected */ 
  } 
  return (result); 
} 

這樣的事情會起作用嗎?

聽起來您正在尋找自己進行底層算術的解決方案。

您是否考慮過使用現有的bignum軟件包,例如GNU Multi Precision Arithmetic庫 擁有現有代碼后,轉換它非常容易。 例如,此代碼:

result += ((ctemp-'0') * power);
power *= 10;

變成:

mpz_t tmp;
mpz_init(tmp);
mpz_mul_ui(tmp, power, ctemp - '0');
mpz_add(result, result, tmp);
mpz_clear(tmp);

mpz_mul_ui(power, power, 10);

暫無
暫無

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

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