tags:

views:

132

answers:

1

Please provide some code for converting char[] array of decimal values to bytes array for big integer value in c.

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.,

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 ?

A: 

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? 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);
R Samuel Klatchko
I think "big" isn't referring to the size of the numbers, just the size of the array of numeric strings. I understood that the OP wants numbers in the range of `long`.
Carl Smotricz
@Carl - Notice the OP writes "I get the result as array of long bytes" Since he's asking for an *array* of longs, it sure sounds like they are looking for a something bigger then just a long.
R Samuel Klatchko
Hmm. I agree it could have been me that misunderstood the question, your interpretation is plausible too.
Carl Smotricz