---
title: "java中hex转byte问题"
author: "GhostWolf"
date: "2015-08-23T20:51:42Z"
tags: []
categories: ["编程语言"]
slug: "java-hex-byte"
draft: false
lastmod: "2015-08-23T20:51:42Z"
id: 2237463
url: "https://ghostwolf.iteye.com/blog/2237463"
---

今天在写个程序，把服务端16进制串再转成base64编码，传给体重硬件，但是碰到个问题，如下：

 

年龄、性别、身高，这三个数值需要用10进制转16进制，OK，我们用了Integer.toHexString(age)进行处理，这里转出来的是16进制，并且把这三个值拼凑成一个字符串。

 

那么问题来了，base64位是需要用byte来转的，我们一不小心，直接就使用jdk中字符串.getBytes()方法，完全把16进制字符串的意思改变了，转出来的码也不一样。最后上网才知道hex串需要按照字节一个个去转。

 

```
public static  byte[] hex2Bytes( String hex ) {
		if( isEmpty(hex) || hex.length() %2> 0 ) {
			log.error("hex2Bytes: invalid HEX string:" + hex );
			return null;
		}
		int len = hex.length() / 2;
		byte[] ret = new byte[ len ];
		int k = 0;
		for (int i = 0; i < len; i++) {
			int c = hex.charAt(k++);
			if( c>='0'&& c<='9' )
				c = c-'0';
			else if( c>='a'&& c<='f' )
				c = c-'a'+ 10;
			else if( c>='A'&& c<='F' )
				c = c-'A'+ 10;
			else {
				log.error("hex2Bytes: invalid HEX string:" + hex );
				return null;
			}
			ret[i]= (byte)(c<<4);
			c = hex.charAt(k++);
			if( c>='0'&& c<='9' )
				c = c-'0';
			else if( c>='a'&& c<='f' )
				c = c-'a'+ 10;
			else if( c>='A'&& c<='F' )
				c = c-'A'+ 10;
			else {
				log.error("hex2Bytes: invalid HEX string:" + hex );
				return null;
			}
			ret[i]+= (byte)c;
		}
		return ret;
	}	
```