繁体   English   中英

在C ++中将md5字​​符串转换为以62为基数的字符串

[英]convert md5 string to base 62 string in c++

我试图在C ++中将md5字​​符串(基于16)转换为基于62的字符串。 到目前为止,我找到的所有转换为以62为底的解决方案都只有在您可以将数字表示为64位整数或更小值的情况下才有效。 一个md5字符串是128位,我自己没有得到任何帮助。

我应该只包括bigint库并完成它吗?

让我们来看看。 128 / log2(62)= 21.497。 这意味着您需要22个“数字”来表示以62为基数的表示形式。

如果您只对不超过22个字符且不超过62个不同字符的字符串表示感兴趣, 则不需要真正的base-62表示。 您可以将128位分解为较小的部分,并分别进行编码。 这样,您将不需要任何128位算术运算。 您可以将128位拆分为2x64位,并使用长度为11的字符串对每个64位块进行编码。这样做甚至可以仅使用57个不同的字符。 因此,您可以消除62个字符中的5个,以避免出现任何“视觉歧义”。 例如,删除l,1,B,8。 剩下58个不同的字符,而11 * log2(58)= 64.438足以编码64位。

获取两个64位块并不困难:

#include <climits>

#if CHAR_BIT != 8
#error "platform not supported, CHAR_BIT==8 expected"
#endif

// 'long long' is not yet part of C++
// But it's usually a supported extension
typedef unsigned long long uint64;

uint64 bits2uint64_bigendian(unsigned char const buff[]) {
   return (static_cast<uint64>(buff[0]) << 56)
        | (static_cast<uint64>(buff[1]) << 48)
        | (static_cast<uint64>(buff[2]) << 40)
        | (static_cast<uint64>(buff[3]) << 32)
        | (static_cast<uint64>(buff[4]) << 24)
        | (static_cast<uint64>(buff[5]) << 16)
        | (static_cast<uint64>(buff[6]) <<  8)
        |  static_cast<uint64>(buff[7]);
}

int main() {
   unsigned char md5sum[16] = {...};
   uint64 hi = bits2uint64_bigendian(md5sum);
   uint64 lo = bits2uint64_bigendian(md5sum+8);
}

为简单起见,您可以使用我的uint128_t c ++类( http://www.codef00.com/code/uint128.h )。 有了它,基本转换器将看起来像这样简单:

#include "uint128.h"
#include <iostream>
#include <algorithm>

int main() {
    char a[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    uint128_t x = U128_C(0x130eb6003540debd012d96ce69453aed);

    std::string r;
    r.reserve(22); // shouldn't result in more than 22 chars 
                   // 6-bits per 62-bit value means (128 / 6 == 21.3)

    while(x != 0) {
        r += a[(x % 62).to_integer()];
        x /= 62;
    }

    // when converting bases by division, the digits are reversed...fix that :-)
    std::reverse(r.begin(), r.end());
    std::cout << r << std::endl;
}

打印:

J7JWEJ0YbMGqaJFCGkUxZ

GMP为任意精度整数提供了便捷的c ++绑定

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM