[C中从Base64到Base10的解码

问题描述 投票:-1回答:2

我是编程新手,正在尝试将十进制数转换为base64并再次返回。我的代码的编码部分有效,但是我无法使解码部分有效。有人可以帮忙吗?

/*
 ============================================================================
 Name        : base64.c
 Author      : Peter Doyle
 Version     :
 Copyright   : Your copyright notice
 Description : Hello World in C, Ansi-style
 ============================================================================
 */

#include <stdio.h>
#include <stdlib.h>

static char *base64enc(long unsigned int value)
{
    char base64[64] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    /* log(2**64) / log(64) = 12.38 => max 13 char + '\0' */
    char buffer[12];
    unsigned int offset = sizeof(buffer);

    buffer[--offset] = '\0';
    do {
        buffer[--offset] = base36[value % 64];
    } while (value /= 64);

    return strdup(&buffer[offset]);
}


int base2base(unsigned char in[], int basein, int baseout)
{
    int J;
    int K;
    int DecimalValue;

    int InputNumberLength;

    //unsigned char OutputValue[];

    unsigned char NumericBaseData[]={"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"};

    //convert input number to base 10.
    InputNumberLength = sizeof(in);
    DecimalValue = 0;
    for (J = 0; J < InputNumberLength; J++){
        for (K = 0; K < basein; K++){
            char sub1;
            char sub2;
            char inJ = (in+J);
            char NumericBaseDataK = (NumericBaseData+K);
            strncpy(sub1, inJ, 1);
            strncpy(sub2, NumericBaseDataK, 1);
                if (sub1 == sub2){
                    int Calc = ((K-1)*(pow(basein,(InputNumberLength-J)))+.5);
                    DecimalValue = DecimalValue+Calc;
                }
        }
    }
    return DecimalValue;
}

int main(void) {
    long unsigned int test = 6000;
    char *encoded = base36enc(test);
    puts(encoded);
    base2base(encoded, 64, 10);
    printf("%d\n", DecimalValue);
    return EXIT_SUCCESS;
c base64 base
2个回答
0
投票

如果str是您在64处有数字的字符串,只需执行以下操作即可将其转换为10进制:

int function(static char *str)
{
int i = 0;
int decimal = 0;
int mult = 1;
while (str[i])
   i++;
i--;
while (i >= 0)
   {
       decimal += mult * get_index(str[i]);
       i--;
       mult = mult * 64;
   }
return decimal;
}

其中get_index获取NumericBaseData中char str [i]的索引Tbh我没有测试它,但是应该可以工作

编辑:get_index会像这样]

int get_index(char c)
{
    char base64[64] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    int i = 0;
    while (c != base64[i])
         i++;
    return i;

}

[如果使用大数,可能将类型更改为长久的类型,因为基数64的smth可以很快变大]


0
投票

我发现@dietbacon的答案对于解码旧项目中的数据库很有用。因此,我修改了解决方案以利用C ++ -std = c ++ 17。 B64编码非常适合将数字压缩到文件中,例如长度,索引等。

© www.soinside.com 2019 - 2024. All rights reserved.