16进制转字符串

时间:2025-02-15 07:16:10 单机游戏

要将16进制字符串转换为字符串,你可以使用以下方法:

使用Python的binascii模块

```python

import binascii

def hex_to_str(hex_data):

str_data = binascii.unhexlify(hex_data)

return str_data.decode('utf-8')

示例

hex_string = "e4bda0e5a5bd"

print(hex_to_str(hex_string)) 输出: 你好

```

使用Java的`Integer.parseInt()`方法

```java

public class HexToString {

public static void main(String[] args) {

String hexString = "48656c6c6f20576f726c64";

byte[] bytes = new byte[hexString.length() / 2];

for (int i = 0; i < hexString.length(); i += 2) {

bytes[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character.digit(hexString.charAt(i + 1), 16));

}

String str = new String(bytes, StandardCharsets.UTF_8);

System.out.println(str); // 输出: Hello World

}

}

```

使用C++的`std::stoi()`函数

```cpp

include

include

include

std::string hexToString(const std::string& hex) {

std::string result;

for (size_t i = 0; i < hex.length(); i += 2) {

std::string byteString = hex.substr(i, 2);

unsigned char byte = (unsigned char) std::stoi(byteString, nullptr, 16);

result += std::string(1, byte);

}

return result;

}

int main() {

std::string hex = "48656c6c6f20576f726c64";

std::string str = hexToString(hex);

std::cout << str << std::endl; // 输出: Hello World

return 0;

}

```

这些方法都可以将16进制字符串转换为对应的字符串。选择哪种方法取决于你使用的编程语言和具体需求。