Java tutorial
/* * Copyright 2012 Kazumune Katagiri. (http://d.hatena.ne.jp/nemuzuka) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ package jp.co.nemuzuka.utils; import org.apache.commons.lang.StringUtils; /** * 16?Utils. * @author k-katagiri */ public class BinaryHexConverter { /** * byte??16??? * @param fromByte ?Byte? * @return 16???(?byte??null???null) */ public static String bytesToHexString(byte[] fromByte) { if (fromByte == null) { return null; } StringBuilder hexStrBuilder = new StringBuilder(); for (int i = 0; i < fromByte.length; i++) { // 16?1??????2?0?? if ((fromByte[i] & 0xff) < 0x10) { hexStrBuilder.append("0"); } hexStrBuilder.append(Integer.toHexString(0xff & fromByte[i]).toUpperCase()); } return hexStrBuilder.toString(); } /** * 16?Byte???? * @param fromHexStr ??16 * @return ??Byte?(??16?null????null) */ public static byte[] hexStringToBytes(String fromHexStr) { if (StringUtils.isEmpty(fromHexStr)) { return null; } //16??2?1?????? //Byte???????????1/2?? byte[] toByte = new byte[fromHexStr.length() / 2]; //16?2??Byte??????? for (int i = 0; i < toByte.length; i++) { toByte[i] = (byte) Integer.parseInt(fromHexStr.substring(i * 2, (i + 1) * 2), 16); } return toByte; } }