---
title: "PHP的pack(\"H*\", $str)转换为java函数"
author: "lam"
date: "2013-11-14T14:08:50Z"
tags: []
categories: ["编程语言"]
slug: "php-pack-h-str-java"
draft: false
lastmod: "2013-11-14T14:08:50Z"
id: 1974691
url: "https://lam.iteye.com/blog/1974691"
---

最近在接一个PHP的接口,使用到pack("H*", $str),怎么进行转换呢,如下:


```java

public static byte[] str2pack(String str) {
	int nibbleshift = 4;
	int position = 0;
	int len = str.length()/2 + str.length()%2;
	
	byte[] output = new byte[len];
	for (char v : str.toCharArray()) {
		byte n = (byte) v;
		if (n >= '0' && n <= '9') {
			n -= '0';
		} else if (n >= 'A' && n <= 'F') {
			n -= ('A' - 10);
		} else if (n >= 'a' && n <= 'f') {
			n -= ('a' - 10);
		} else {
			continue;
		}
		
		output[position] |= (n << nibbleshift);

		if (nibbleshift == 0) {
			position++;
		}
		nibbleshift = (nibbleshift + 4) & 7;
	}
	
	return output;
}

```