dongsi1954 2016-12-13 20:41
浏览 679
已采纳

PHP:Base64解码将字符串转换为其他格式,如十进制或二进制

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/

  • 写回答

1条回答 默认 最新

  • dongzhiyi2006 2016-12-13 21:07
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试