常用语音转换-str2hex_hex2str

本文介绍了两个Python函数str2hex和hex2str,用于将字符串转换为十六进制和从十六进制还原回字符串,展示了如何在命令行中使用这些工具进行数据转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. str2hex_hex2str

1.1. python 实现 hex2str, str2hex

python 实现字符串和16进制字符串相互转换

import sys

def str2hex(input_data: str) -> str:
    """将字符串转换为十六进制表示"""
    byte_data = input_data.encode('utf-8')
    return byte_data.hex()

def hex2str(hex_string: str) -> str:
    """将十六进制字符串转换回原始字符串"""
    try:
        byte_data = bytes.fromhex(hex_string)
        return byte_data.decode('utf-8')
    except ValueError as e:
        print(f"错误: 无效的十六进制字符串 - {e}")
        return None

# python str2hex.py str1 str2
if __name__ == "__main__":
    if "68656c6c6f" == str2hex("hello"):
            print("hello hex is 68656c6c6f")
    for i in range(len(sys.argv)-1):
        hex = str2hex(sys.argv[i+1])
        str_data = hex2str(hex)
        print(str_data, hex)
python str2hex.py str1 str2

hello hex is 68656c6c6f
str1 73747231
str2 73747232

1.2. C 实现 hex2str, str2hex

#include <ctype.h>
#include <stdio.h>
#include <string.h>

// 将字符串转换为十六进制字符串,返回实际转换的字节数(成功)或 -1(失败)
int str2hex(char *hex, unsigned int hex_len, unsigned char *str, unsigned int str_len) {
    int i;
    if (str_len * 2 > hex_len - 1) {
        printf("dst buf is not enough! Need %u bytes, but only %u available.\n", str_len * 2 + 1, hex_len);
        return -1;
    }

    for (i = 0; i < str_len; i++) {
        if (snprintf(hex + 2 * i, 3, "%02x", str[i]) != 2) {
            printf("Error converting byte at position %d\n", i);
            return -1;
        }
    }
    return i; // 返回转换的字节数
}

// 将十六进制字符串转换为字节数组,返回实际转换的字节数(成功)或 -1(失败)
int hex2str(const char *src, unsigned char *dst, unsigned int dst_len) {
    unsigned int src_len = strlen(src);
    unsigned int i, j;

    // 检查源字符串长度是否为偶数(每个字节对应两个十六进制字符)
    if (src_len % 2 != 0) {
        printf("Invalid hex string length (must be even)\n");
        return -1;
    }

    // 检查目标缓冲区是否足够大
    if (src_len / 2 > dst_len) {
        printf("dst buf is not enough! Need %u bytes, but only %u available.\n", src_len / 2, dst_len);
        return -1;
    }

    // 转换十六进制字符串为字节数组
    for (i = 0, j = 0; i < src_len; i += 2, j++) {
        char high = toupper(src[i]);
        char low = toupper(src[i + 1]);
        unsigned char value = 0;

        // 转换高4位
        if (high >= '0' && high <= '9') {
            value = (high - '0') << 4;
        } else if (high >= 'A' && high <= 'F') {
            value = (high - 'A' + 10) << 4;
        } else {
            printf("Invalid hex character at position %d: %c\n", i, high);
            return -1;
        }

        // 转换低4位并组合
        if (low >= '0' && low <= '9')
            value |= low - '0';
        else if (low >= 'A' && low <= 'F')
            value |= low - 'A' + 10;
        else {
            printf("Invalid hex character at position %d: %c\n", i + 1, low);
            return -1;
        }

        dst[j] = value;
    }

    return j; // 返回转换后的字节数
}

int main(void) {
    const char *original_str = "hello";
    unsigned int str_len = strlen(original_str);

    // 存储十六进制表示(11字节:10个字符+终止符)
    char hex_str[11] = {0};
    int hex_result = str2hex(hex_str, sizeof(hex_str), (unsigned char *)original_str, str_len);

    if (hex_result >= 0) {
        printf("str -> hex: %s -> %s (bytes converted: %d)\n", original_str, hex_str, hex_result);
    } else {
        printf("Failed to convert string to hex\n");
        return 1;
    }

    // 转换回字符串(6字节:5个字符+终止符)
    char decoded_str[6] = {0};
    int str_result = hex2str(hex_str, (unsigned char *)decoded_str, sizeof(decoded_str));
    if (str_result >= 0) {
        printf("hex -> str: %s -> %s (bytes decoded: %d)\n", hex_str, decoded_str, str_result);
    } else {
        printf("Failed to convert hex to string\n");
        return 1;
    }

    return 0;
}
gcc main.c
./a.out
str -> hex: hello -> 68656c6c6f (bytes converted: 5)
hex -> str: 68656c6c6f -> hello (bytes decoded: 5)

1.3. golang 实现 hex2str, str2hex

package main

import (
	"encoding/hex"
	"fmt"
	"os"
)

// StrToHex 将字符串转换为十六进制表示
func StrToHex(s string) string {
	return hex.EncodeToString([]byte(s))
}

// HexToStr 将十六进制字符串转换回原始字符串
func HexToStr(hexStr string) (string, error) {
	bytes, err := hex.DecodeString(hexStr)
	if err != nil {
		return "", fmt.Errorf("无效的十六进制字符串: %v", err)
	}
	return string(bytes), nil
}

func main() {
	// 自检示例
	testStr := "hello"
	expectedHex := "68656c6c6f"
	actualHex := StrToHex(testStr)
	
	if actualHex == expectedHex {
		fmt.Printf("测试通过: '%s' 的十六进制表示是 %s\n", testStr, expectedHex)
	} else {
		fmt.Printf("测试失败: '%s' 的十六进制表示应为 %s,但得到 %s\n", testStr, expectedHex, actualHex)
	}
}
go run main.go  
测试通过: 'hello' 的十六进制表示是 68656c6c6f
用法: go run str2hex.go [字符串1] [字符串2] ...

1.4. java 实现 hex2str, str2hex

import java.nio.charset.StandardCharsets;

public class HexConverter {

    // 将字符串转换为十六进制表示
    public static String strToHex(String input) {
        if (input == null) {
            return null;
        }
        byte[] bytes = input.getBytes(StandardCharsets.UTF_8);
        StringBuilder result = new StringBuilder();
        for (byte b : bytes) {
            result.append(String.format("%02x", b));
        }
        return result.toString();
    }

    // 将十六进制字符串转换回原始字符串
    public static String hexToStr(String hexInput) throws IllegalArgumentException {
        if (hexInput == null || hexInput.length() % 2 != 0) {
            throw new IllegalArgumentException("无效的十六进制字符串:长度必须为偶数");
        }
        int len = hexInput.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(hexInput.charAt(i), 16) << 4)
                                 + Character.digit(hexInput.charAt(i+1), 16));
        }
        return new String(data, StandardCharsets.UTF_8);
    }

    public static void main(String[] args) {
        // 自检示例
        String testStr = "hello";
        String expectedHex = "68656c6c6f";
        String actualHex = strToHex(testStr);
        
        if (expectedHex.equals(actualHex)) {
            System.out.printf("测试通过: '%s' 的十六进制表示是 %s%n", testStr, expectedHex);
        } else {
            System.out.printf("测试失败: '%s' 的十六进制表示应为 %s,但得到 %s%n", 
                             testStr, expectedHex, actualHex);
        }
    }
}
javac HexConverter.java
java HexConverter      
测试通过: 'hello' 的十六进制表示是 68656c6c6f
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值