简体   繁体   English

将十进制数组(str)转换为二进制数组(bytes)

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

Please provide some code for converting char[] array of decimal values to bytes array for big integer value in c. 请提供一些代码,将c的大整数值的十进制值的char []数组转换为bytes数组。

How can I convert this below code for big array of decimal value, such as I get the result as array of long 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);
}

No it is not just long value , it is really a biginteger value , can anyone give a simple dec to byte(binary conversion logic , i will replace the int with my bigint implementations and bigint operators(add, mult) etc., 不,它不仅仅是long值,它实际上是biginteger值,任何人都可以将dec转换为字节(二进制转换逻辑,我将用我的bigint实现和bigint运算符(add,mult)等替换int,

Samuel is correct! 塞缪尔是对的!

Thanks in advance. 提前致谢。

For Example i can replace the above as below 例如我可以替换以下内容

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

something like this will work ? 这样的事情会起作用吗?

It sounds like you are looking for a solution where you do the low level arithmetic yourself. 听起来您正在寻找自己进行底层算术的解决方案。

Have you considered using an existing bignum package such as the GNU Multi Precision Arithmetic library ? 您是否考虑过使用现有的bignum软件包,例如GNU Multi Precision Arithmetic库 It's pretty easy to convert your existing code once you have that. 拥有现有代码后,转换它非常容易。 For example, this code: 例如,此代码:

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

becomes: 变成:

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