JAVA/C#/Python/Javascript/C/C++ 十六进制与字符串的转换

unimof 2021年02月26日 431次浏览

在物联网开发过程中,经常需要将直接数组转换为16进制进行输出,不同语言的二进制和16进制都如何进行相互转换呢?

一、Java

/**
 * 字符串转换成为16进制(无需Unicode编码)
 * @param str
 * @return
 */
public static String str2HexStr( String str )
{
    char[] chars = "0123456789ABCDEF".toCharArray();
    StringBuilder sb = new StringBuilder( "" );
    byte[] bs = str.getBytes();
    int bit;
    for ( byte b : bs )
    {
        bit = (b & 0x0f0) >> 4;
        sb.append( chars[bit] );
        bit = b & 0x0f;
        sb.append( chars[bit] );
    }
    return(sb.toString().trim() );
}


/**
* 16进制直接转换成为字符串(无需Unicode解码)
* @param hexStr
* @return
*/
public static String hexStr2Str( String hexStr )
{
    String str = "0123456789ABCDEF";
    char[] hexs	= hexStr.toCharArray();
    byte[] bytes	= new byte[hexStr.length() / 2];
    int n;
    for ( int i = 0; i < bytes.length; i++ )
    {
        n		= str.indexOf( hexs[2 * i] ) * 16;
        n		+= str.indexOf( hexs[2 * i + 1] );
        bytes[i]	= (byte) (n & 0xff);
    }
    return(new String( bytes ) );
}

二、C#

private string StringToHexString(string s,Encoding encode)
{
    byte[] b = encode.GetBytes(s);//按照指定编码将string编程字节数组
    string result = string.Empty;
    for (int i = 0; i < b.Length; i++)//逐字节变为16进制字符,以%隔开
    {
        result += "%"+Convert.ToString(b[i], 16);
    }
    return result;
}

private string HexStringToString(string hs, Encoding encode)
{
    //以%分割字符串,并去掉空字符
    string[] chars = hs.Split(new char[]{'%'},StringSplitOptions.RemoveEmptyEntries);
    byte[] b = new byte[chars.Length];
    //逐个字符变为16进制字节数据
    for (int i = 0; i < chars.Length; i++)
    {
        b[i] = Convert.ToByte(chars[i], 16);
    }
    //按照指定编码将字节数组变为字符串
    return encode.GetString(b);
} 

三、Python

def hex2char(data):
#    binascii.a2b_hex(hexstr) 
    output = binascii.unhexlify(data)
    print(output)

def char2hex(data):
    data = b'data'
#    binascii.b2a_hex(data) 
    output = binascii.hexlify(data)
    print(output)

四、JavaScript

function stringToHex(str) {

  var val = "";

  for(var i = 0; i < str.length; i++) {

    if(val == "") { val = str.charCodeAt(i).toString(16); } else { val += "," + str.charCodeAt(i).toString(16); }
  }
  return val;
}

 function hexToString(str){

    var val="";

    var arr = str.split(",");

    for(arr i = 0; i < arr.length; i++){

      val += String.fromCharCode(parseInt(arr[i],16));

    }

    return val;

  }

五、C/C++


/* ASCII字符 '0'  '1'  '2'  '3'  '4'  '5'  '6'  '7'  '8'  '9' 
 * ASCII码值 0x30 0x31 0x32 0x33 0x34 0x35 0x36 0x37 0x38 0x39 
 */
 
typedef unsigned char uint8_t;
 
//判断是否是十六进制的基数
int isHexNum(uint8_t _hexNum)
{
	if('0'<=_hexNum && _hexNum<='9')
	{
		return 1;
	}
	else if('A'<=_hexNum && _hexNum<='F')
	{
		return 2;
	}
	else if('a'<=_hexNum && _hexNum<='f')
	{
		return 3;
	}
	return -1;
}
 
void numToHexStr(uint8_t _hexNum, uint8_t* _hexStr)
{
	uint8_t tmp;
	
	if(NULL == _hexStr)
	{
		return;
	}
	
	//低4bit
	tmp = (_hexNum >> 4) & 0x0f;
	if(tmp <= 9)
		*_hexStr = tmp+'0';
	else
		*_hexStr = tmp-0x0a + 'A';
	
	_hexStr++;
	
	//高4bit
	tmp = _hexNum & 0x0f;	
	if(tmp <= 9)
		*_hexStr = tmp+'0';
	else
		*_hexStr = tmp-0x0a + 'A';
}
 
//将字符串转为16进制形式,以查看不可见字符 "01" ==> "3031"
int toHexStr(const uint8_t* _str, uint8_t *_hexStr)
{
	int i;
	int len;
	uint8_t* resultPtr;
	if(NULL == _str || NULL == _hexStr)
	{
		return -1;
	}
	
	len = strlen(_str);
	resultPtr = _hexStr;
	for(i=0; i<len; i++)
	{
		numToHexStr(_str[i], resultPtr);
		resultPtr += 2;
	}
	return strlen(_hexStr);
}
 
//十六进制的字符转数字
uint8_t charToHexNum(uint8_t hexChar)
{
	uint8_t tmp;
	if(1>isHexNum(hexChar))
	{
		return 0xFF;
	}	
	
	if(hexChar<='9')
	{
		tmp = hexChar-'0';
	}
	else if(hexChar<='F')
	{
		tmp = hexChar-'7';
	}
	else
	{
		tmp = hexChar-'W';
	}
	return tmp;
}
 
//将16进制形式的字符串转为文本形式 "3031" ==> "01"
int hexToStr(const uint8_t* _hexStr, uint8_t* _str)
{
	int i;
	int len;
	uint8_t* ptr;
	if(NULL == _str || NULL == _hexStr)
	{
		return -1;
	}
	
	len = strlen(_hexStr);
	ptr = _str;
	
	//要是单数个字符,则最后一个会被丢弃
	for(i=0; i<len-1;i++)
	{
		//是十六进制的基数才转换
		//if(0<isHexNum(_hexStr[i]))
		{			
			*ptr = charToHexNum(_hexStr[i])*16;			
			i++;
			*ptr += charToHexNum(_hexStr[i]);
			ptr++;
		}
	}
			
	return strlen(_str);
}