Sean Hill
Sean Hill

Reputation: 1327

Converting Base64 to Hex confusion

I was working on a problem for converting base64 to hex and the problem prompt said as an example:

3q2+7w== should produce deadbeef

But if I do that manually, using the base64 digit set ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/ I get:

3 110111
q 101010
2 110110
+ 111110
7 111011
w 110000

As a binary string:

110111 101010 110110 111110 111011 110000

grouped into fours:

1101 1110 1010 1101 1011 1110 1110 1111 0000

to hex

d e a d b e e f 0

So shouldn't it be deadbeef0 and not deadbeef? Or am I missing something here?

Upvotes: 0

Views: 1039

Answers (1)

jps
jps

Reputation: 22465

Base64 is meant to encode bytes (8 bit).

Your base64 string has 6 characters plus 2 padding chars (=), so you could theoretically encode 6*6bits = 36 bits, which would equal 9 4bit hex numbers. But in fact you must think in bytes and then you only have 4 bytes (32 bits) of significant information. The remaining 4 bits (the extra '0') must be ignored.

You can calculate the number of insignificant bits as:

y : insignificant bits
x : number of base64 characters (without padding)

y = (x*6) mod 8

So in your case:

y = (6*6) mod 8 = 4

So you have 4 insignificant bit on the end that you need to ignore.

Upvotes: 1

Related Questions