Sha256: 1a1af317b410a729baae48ef4990ad6886ba2ff83f08b3a31a07c15d5d24e299

Contents?: true

Size: 1.14 KB

Versions: 50

Compression:

Stored size: 1.14 KB

Contents

#include "all_your_base.h"
#include <math.h>
#include <string.h>

size_t rebase(int8_t digits[DIGITS_ARRAY_SIZE], int16_t fromBase,
              int16_t toBase, size_t numDigits)
{
   uint16_t denary = 0;
   size_t newNumDigits = 0;

   if ((fromBase <= 1) || (toBase <= 1) || (numDigits <= 0))
      return 0;                 /* invalid bases or length */
   if (digits[0] == 0)
      return 0;                 /* leading zeros */

   /* convert to denary */
   for (size_t i = 0; i < numDigits; ++i) {
      if (digits[i] < 0)
         return 0;              /* negative digits */
      if (digits[i] >= fromBase)
         return 0;              /* invaid positive digit */
      denary += digits[i] * pow(fromBase, (numDigits - i - 1));
   }

   /* calculate number of new digits */
   for (uint16_t j = denary; j > 0;) {
      j /= toBase;
      ++newNumDigits;
   }

   /* calculate and store new digits */
   for (size_t i = newNumDigits - 1; denary > 0; --i) {
      digits[i] = denary % toBase;
      denary /= toBase;
   }

   /* ensure rest of array is zero */
   memset(&digits[newNumDigits], 0, DIGITS_ARRAY_SIZE - newNumDigits);

   return newNumDigits;
}

Version data entries

50 entries across 50 versions & 1 rubygems

Version Path
trackler-2.2.1.40 tracks/c/exercises/all-your-base/src/example.c
trackler-2.2.1.39 tracks/c/exercises/all-your-base/src/example.c
trackler-2.2.1.38 tracks/c/exercises/all-your-base/src/example.c
trackler-2.2.1.37 tracks/c/exercises/all-your-base/src/example.c
trackler-2.2.1.36 tracks/c/exercises/all-your-base/src/example.c
trackler-2.2.1.35 tracks/c/exercises/all-your-base/src/example.c
trackler-2.2.1.34 tracks/c/exercises/all-your-base/src/example.c
trackler-2.2.1.33 tracks/c/exercises/all-your-base/src/example.c
trackler-2.2.1.32 tracks/c/exercises/all-your-base/src/example.c
trackler-2.2.1.31 tracks/c/exercises/all-your-base/src/example.c
trackler-2.2.1.30 tracks/c/exercises/all-your-base/src/example.c
trackler-2.2.1.29 tracks/c/exercises/all-your-base/src/example.c
trackler-2.2.1.28 tracks/c/exercises/all-your-base/src/example.c
trackler-2.2.1.27 tracks/c/exercises/all-your-base/src/example.c
trackler-2.2.1.26 tracks/c/exercises/all-your-base/src/example.c
trackler-2.2.1.25 tracks/c/exercises/all-your-base/src/example.c
trackler-2.2.1.24 tracks/c/exercises/all-your-base/src/example.c
trackler-2.2.1.23 tracks/c/exercises/all-your-base/src/example.c
trackler-2.2.1.22 tracks/c/exercises/all-your-base/src/example.c
trackler-2.2.1.21 tracks/c/exercises/all-your-base/src/example.c