Bing
Bing

Reputation: 3171

PHP: Base64 decode to convert string to other formats like decimal or binary

I'm trying to use a service which "base64 converts" their data which they then push to my server. The data is divided into three data types: strings, integers and booleans. Why they package it this way I don't understand, but it's up to me to decipher it.

I have a string Qjo0MDk2 which should convert to B:4096 and PHP's native base64_decode function works!

However, if I try to convert AAATmg== to a base-10 (decimal) integer value, I want to get 5018, but base64_decode just gives me nothing. (I assume because it's trying to convert to a string, rather than a base-10 integer.)

Likewise, AA== should convert to 0 in base-2 (binary) boolean values, while AQ== should convert to 1 in the same.

Is there a set of functions that does this already somewhere? I can't imagine this is new. Here is a website that does it today, but the code is not exposed: https://conv.darkbyte.ru/

Upvotes: 0

Views: 1063

Answers (1)

Charlotte Dunois
Charlotte Dunois

Reputation: 4680

Binary data can't be simply printed, that's why you don't see something from base64_decode, but the data is there. If you want to actually see something, you need to convert the data to hexadecimal (technically into a hexadecimal representation). Since it looks like that the third party application is doing that (though in the other direction), you will have to do that for all data.

The data representation for AA== and AQ== is the same when you use them in an if statement, even though they are 00 and 01 hexadecimal-wise. They're true-ish to PHP, thus executing the if part. If you actually want to check their state, you will have to convert them to int (from the hexadecimal representation).

(int) bin2hex(base64_decode("AA==")) // int(0)
(int) bin2hex(base64_decode("AQ==")) // int(1)

Trying to convert from binary to int directly will result in int(0). So you have to be cautious when you deal with data from the third party application.

Upvotes: 4

Related Questions