开发者

Converting a BASE64 string to a BASE16(HEX) string?

Hey, I'm trying to write a program to convert from a BASE64 string to a BASE16(HEX) string.

Here's an example:

     BASE64:   Ba7+Kj3N
HEXADECIMAL:   05 ae fe 2a 3d cd
     BINARY:   00000101 10101110 11111110 00101010 00111101 11001101
    DECIMAL:   5 174 254 42 61 205

What's the logic to convert from BASE64 to HEXIDECIMAL?

Why is the decimal representation split up?

How come t开发者_StackOverflow社区he binary representation is split into 6 section?

Just want the math, the code I can handle just this process is confusing me. Thanks :)


Read the base64 4 chars at a time, since 4 base64 chars become 3 bytes:

'Ba7+', 'Kj3N'

Decode each char of the base64. I just looked it up on Wikipedia:

[1, 26, 59, 62], [10, 35, 55, 13]

Shift the numbers in each group to the left by 18, 12, 6, and 0 respectively:

>>> def pack(a, b, c, d): return hex((a << 18) + (b << 12) + (c << 6) + d)
>>> pack(1, 26, 59, 62)
'0x5aefe'
>>> pack(10, 35, 55, 13)
'0x2a3dcd'

Then, if you want to convert to hex yourself, shift them to the right by 4, 8, ... 24, 28 to peel off each nybble and convert to a digit from 0 to f.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜