[英]Why isn't this base64 decode/encode function working properly?
我從這里開始使用base64函數嘗試運行一個簡單的程序。 我想使用以下代碼將二進制文件轉換為base64:
int x = 1;
std::string data = base64_encode(reinterpret_cast<unsigned char *>((void *)&x), 4);
std::string out = base64_decode(data);
int y = reinterpret_cast<int>(out.data());
調用encode函數,並生成此字符串"AQAAAA=="
。 根據我的理解,如果將其解碼並轉換為字節,則應該轉換為01 00 00 0
(我實際上不明白為什么是7字節)。 調用解碼函數時,我期望01 00 00 00
,然后可以將reinterpret_castable返回整數1,但是我得到的不是"\\001\\000\\000"
。 我嘗試增加編碼函數的第二個參數,很有趣,它在解碼后給了我正確的答案"\\001\\000\\000\\000"
。
假設您正在將此代碼用於base64,我懷疑以下方法會起作用:
int x = 1;
std::string data = base64_encode(reinterpret_cast<unsigned char *>(&x), 4);
std::string out = base64_decode(data);
int y= *(reinterpret_cast<int*>(out.c_str()));
在執行解碼邏輯的任何方面,它都應該在進行此轉換之前驗證out.size() == sizeof(int)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.