gpt4 book ai didi

php - C++ HexToBin VS PHP Hex2Bin 函数。输出不同

转载 作者:太空宇宙 更新时间:2023-11-04 12:54:45 24 4
gpt4 key购买 nike

我的 PHP 和 C++ 脚本中都有以下字符串:

152F302436152F302435152F302434152F302433152F302433

在 PHP 中,我将内置的 hex2bin 函数用作:

<?php
$HEXString = "152F302436152F302435152F302434152F302433152F302433";
echo hex2bin($HEXString);
//Outputs: /0$6/0$5/0$4/0$3/0$3
?>

但是,在 C++ 中,我使用以下函数来完成相同的操作并得到完全不同的结果:

const char* HexCharToBin(char c) {
char cUpper = toupper(c);
if (cUpper == '0') return "0000";
else if (cUpper == '1') return "0001";
else if (cUpper == '2') return "0010";
else if (cUpper == '3') return "0011";
else if (cUpper == '4') return "0100";
else if (cUpper == '5') return "0101";
else if (cUpper == '6') return "0110";
else if (cUpper == '7') return "0111";
else if (cUpper == '8') return "1000";
else if (cUpper == '9') return "1001";
else if (cUpper == 'A') return "1010";
else if (cUpper == 'B') return "1011";
else if (cUpper == 'C') return "1100";
else if (cUpper == 'D') return "1101";
else if (cUpper == 'E') return "1110";
else if (cUpper == 'F') return "1111";
else return "0000";
}
string HexToBin(const string& hex) {
string bin;
for (unsigned i = 0; i != hex.length(); ++i) {
bin += HexCharToBin(hex[i]);
}
return bin;
}

C++代码:

cout << HexToBin("152F302436152F302435152F302434152F302433152F302433") << endl;
//Outputs: 00010101001011110011000000100100001101100001010100101111001100000010010000110101000101010010111100110000001001000011010000010101001011110011000000100100001100110001010100101111001100000010010000110011

我希望 C++ 实现与 PHP 返回相同的字符串。我在这里做错了什么?

最佳答案

如果您只想将十六进制数转换为二进制数,请使用 base_convert() .

阅读hex2bin php documentation仔细地引用:

Caution This function does NOT convert a hexadecimal number to a binary number. This can be done using the base_convert() function.

这个功能简直了

Decodes a hexadecimally encoded binary string.

因此,由于您的字符串不是十六进制编码的字符串,您会得到意想不到的/不同的输出。

要复制 php 的 hex2bin 的行为,以下帖子可以帮助您:Missing punctuation from C++ hex2bin

希望对您有所帮助。

关于php - C++ HexToBin VS PHP Hex2Bin 函数。输出不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47073286/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com