C语言 如何将任意大整数从基数10转换为基数16?

scyqe7ek  于 2023-08-03  发布在  其他
关注(0)|答案(8)|浏览(109)

该程序需要输入一个任意大的无符号整数,表示为一个以10为底的字符串。输出是另一个以16为底表示整数的字符串。
例如,输入为“1234567890987654321234567890987654321234567890987654321”,输出应为“CE 3B 5A 137 DD 015278 E09864703 E4 FF 9952 FF 6 B62 C1 CB 1”
算法越快越好。
如果输入被限制在32位或64位整数内,这将是非常容易的;例如,下面的代码可以进行转换:

#define MAX_BUFFER 16
char hex[] = "0123456789ABCDEF";

char* dec2hex(unsigned input) {
    char buff[MAX_BUFFER];
    int i = 0, j = 0;
    char* output;

    if (input == 0) {
        buff[0] = hex[0];
        i = 1;
    } else {
        while (input) {
            buff[i++] = hex[input % 16];
            input = input / 16;
        }
    }

    output = malloc((i + 1) * sizeof(char));
    if (!output) 
        return NULL;

    while (i > 0) {
        output[j++] = buff[--i];        
    }
    output[j] = '\0';

    return output;
}

字符串
真实的具有挑战性的部分是“任意大”的无符号整数。我在谷歌上搜索过,但大多数人都在谈论32位或64位内的转换。没有找到运气。
任何人都可以给予任何点击或任何链接,可以阅读?
先谢谢你。

编辑这是我最近遇到的一个面试问题。谁能简单地解释一下如何解决这个问题?我知道有一个gmp库,我以前用过它;然而,作为面试问题,它要求不使用外部库。

vkc1a9a2

vkc1a9a21#

1.分配一个整数数组,元素的数量等于输入字符串的长度。将数组初始化为全0。
这个整数数组将以16为底存储值。
1.将输入字符串中的十进制数字添加到数组的末尾。将现有值乘以10加上结转,将新值存储在数组中,新结转值为newvalue div 16。

carryover = digit;
for (i = (nElements-1); i >= 0; i--)
{
    newVal = array[index] * 10) + carryover;
    array[index] = newval % 16;
    carryover = newval / 16;
}

字符串
1.打印数组,从第0个条目开始,跳过前导0。
下面是一些可以工作的代码。毫无疑问,可能有一些优化可以进行。但这应该足以作为一个快速和肮脏的解决方案:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "sys/types.h"

char HexChar [16] = { '0', '1', '2', '3', '4', '5', '6', '7',
                      '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

static int * initHexArray (char * pDecStr, int * pnElements);

static void addDecValue (int * pMyArray, int nElements, int value);
static void printHexArray (int * pHexArray, int nElements);

static void
addDecValue (int * pHexArray, int nElements, int value)
{
    int carryover = value;
    int tmp = 0;
    int i;

    /* start at the bottom of the array and work towards the top
     *
     * multiply the existing array value by 10, then add new value.
     * carry over remainder as you work back towards the top of the array
     */
    for (i = (nElements-1); (i >= 0); i--)
    {
        tmp = (pHexArray[i] * 10) + carryover;
        pHexArray[i] = tmp % 16;
        carryover = tmp / 16;
    }
}

static int *
initHexArray (char * pDecStr, int * pnElements)
{
    int * pArray = NULL;
    int lenDecStr = strlen (pDecStr);
    int i;

    /* allocate an array of integer values to store intermediate results
     * only need as many as the input string as going from base 10 to
     * base 16 will never result in a larger number of digits, but for values
     * less than "16" will use the same number
     */

    pArray = (int *) calloc (lenDecStr,  sizeof (int));

    for (i = 0; i < lenDecStr; i++)
    {
        addDecValue (pArray, lenDecStr, pDecStr[i] - '0');
    }

    *pnElements = lenDecStr;

    return (pArray);
}

static void
printHexArray (int * pHexArray, int nElements)
{
    int start = 0;
    int i;

    /* skip all the leading 0s */
    while ((pHexArray[start] == 0) && (start < (nElements-1)))
    {
        start++;
    }

    for (i = start; i < nElements; i++)
    {
        printf ("%c", HexChar[pHexArray[i]]);
    }

    printf ("\n");
}

int
main (int argc, char * argv[])
{
    int i;
    int * pMyArray = NULL;
    int nElements;

    if (argc < 2)
    {
        printf ("Usage: %s decimalString\n", argv[0]);
        return (-1);
    }

    pMyArray = initHexArray (argv[1], &nElements);

    printHexArray (pMyArray, nElements);

    if (pMyArray != NULL)
        free (pMyArray);

    return (0);
}

zzoitvuj

zzoitvuj2#

我写了一个article,它描述了一个简单的Python解决方案,可以用来将一系列数字从任意数字基转换为任意数字基。我最初用C实现了这个解决方案,我不想依赖于外部库。我认为你应该能够用C或任何你喜欢的语言重写非常简单的Python代码。
下面是Python代码:

import math
import string

def incNumberByValue(digits, base, value):
   # The initial overflow is the 'value' to add to the number.
   overflow = value
   # Traverse list of digits in reverse order.
   for i in reversed(xrange(len(digits))):
      # If there is no overflow we can stop overflow propagation to next higher digit(s).
      if not overflow:
         return
      sum = digits[i] + overflow
      digits[i] = sum % base
      overflow = sum / base

def multNumberByValue(digits, base, value):
   overflow = 0
   # Traverse list of digits in reverse order.
   for i in reversed(xrange(len(digits))):
      tmp = (digits[i] * value) + overflow
      digits[i] = tmp % base
      overflow = tmp / base

def convertNumber(srcDigits, srcBase, destDigits, destBase):
   for srcDigit in srcDigits:
      multNumberByValue(destDigits, destBase, srcBase)
      incNumberByValue(destDigits, destBase, srcDigit)

def withoutLeadingZeros(digits):
   for i in xrange(len(digits)):
      if digits[i] != 0:
         break
   return digits[i:]

def convertNumberExt(srcDigits, srcBase, destBase):
   # Generate a list of zero's which is long enough to hold the destination number.
   destDigits = [0] * int(math.ceil(len(srcDigits)*math.log(srcBase)/math.log(destBase)))
   # Do conversion.
   convertNumber(srcDigits, srcBase, destDigits, destBase)
   # Return result (without leading zeros).
   return withoutLeadingZeros(destDigits)

# Example: Convert base 10 to base 16
base10 = [int(c) for c in '1234567890987654321234567890987654321234567890987654321']
base16 = convertNumberExt(base10, 10, 16)
# Output list of base 16 digits as HEX string.
hexDigits = '0123456789ABCDEF'
string.join((hexDigits[n] for n in base16), '')

字符串

vecaoik1

vecaoik13#

真实的具有挑战性的部分是“任意大”的无符号整数。
你试过使用GNU MP Bignum库吗?

vc6uscn9

vc6uscn94#

Unix dc能够对任意大整数进行基转换。开放BSD源代码是可用的here

0vvn1miw

0vvn1miw5#

下面是一个BigInt库:

http://www.codeproject.com/KB/cs/BigInt.aspx?msg=3038072#xx3038072xx

字符串
不知道它是否有效,但这是我在谷歌上找到的第一个。它似乎有解析和格式化大整数的函数,所以它们也可能支持不同的基。

**编辑:**啊,你用的是C,我的错误。但是您可能能够从代码中获得一些想法,或者使用.NET的人可能会有同样的问题,所以我将把它留在这里。

iezvtpos

iezvtpos6#

你可以尝试这个任意长度的input C99base_convert(介于2和62之间)函数:

#include <stdlib.h>
#include <string.h>

static char *base_convert(const char * str, const int base_in, const int base_out) {
    static const char *alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    size_t a, b, c = 1, d;
    char *s = malloc(c + 1);
    strcpy_s(s, c + 1, "0");
    for (; *str; ++str) {
        for (a = (char*)memchr(alphabet, *str, base_in) - alphabet, b = c; b;) {
            d = ((char *)memchr(alphabet, s[--b], base_out) - alphabet) * base_in + a;
            s[b] = alphabet[d % base_out];
            a = d / base_out;
        }
        for (; a; s = realloc(s, ++c + 1), memmove(s + 1, s, c), *s = alphabet[a % base_out], a /= base_out);
    }
    return s;
}

字符串
在线试用-使用示例:

#include <stdio.h>

int main() {
    char * res = base_convert("12345678909876543212345678909876"
                              "54321234567890987654321", 10, 16);
    puts(res);
    free(res);

    // print CE3B5A137DD015278E09864703E4FF9952FF6B62C1CB1
}


示例输出:

'11100100100011101011001001110110001101001001100010100001111011110011000010'
 from base 2 to base 58 is 'BaseConvert62'.

'NdN2mbALtnCHH' from base 60 to base 59 is 'StackOverflow'.


使用您的示例和Fibonacci(1500000)进行了测试。
谢谢。

e4yzc0pl

e4yzc0pl7#

Python皮:

>>> from string import upper
>>> input = "1234567890987654321234567890987654321234567890987654321"
>>> output = upper(hex(int(input)))[2:-1]
>>> print output
CE3B5A137DD015278E09864703E4FF9952FF6B62C1CB1

字符串

hjzp0vay

hjzp0vay8#

下面是上面提到的用JavaScript实现的算法:

function addDecValue(hexArray, value) {
  let carryover = value;
  for (let i = (hexArray.length - 1); i >= 0; i--) {
    let rawDigit = ((hexArray[i] || 0) * 10) + carryover;
    hexArray[i] = rawDigit % 16;
    carryover = Math.floor(rawDigit / 16);
  }
}
    
function toHexArray(decimalString) {
  let hexArray = new Array(decimalString.length);
  for (let i = 0; i < decimalString.length; i++) {
    addDecValue(hexArray, Number(decimalString.charAt(i)));
  }
  return hexArray;
}

function toHexString(hexArray) {
  const hexDigits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'];
  let result = '';
  for (let i = 0; i < hexArray.length; i++) {
    if (result === '' && hexArray[i] === 0) continue;
    result += hexDigits[hexArray[i]];
  }
  return result
}
    
toHexString(toHexArray('1234567890987654321234567890987654321234567890987654321'));

字符串

相关问题