Java converts bytes to hexadecimal code Sharing _java_ Scripting home

Java converts bytes to hexadecimal code sharing

Updated: Jan 15, 2016 11:37:12 Submitted by: hebedich
We know that in java, a byte is a byte, that is, eight bits of binary; Four bits can represent a hexadecimal bit, so a byte can be converted to two hexadecimal bits. Let's take a look at the specific method in detail.

Some of the code in this paper is extracted from the Internet, and a little collated for the conversion between bytes and hexadecimal.

/** * reference apache commons <a * href="http://commons.apache.org/codec/">http://commons.apache.org/codec/</a> * * byte takes 8 bits and hexadecimal characters take 4 bits. Therefore, a byte can be converted into two corresponding hexadecimal characters, that is, the high 4 bits of byte and the low 4 bits * are converted into the corresponding hexadecimal characters H and L, and combined. The same goes for the opposite conversion. ** / public class Hex {/** ** Used to create the output of hexadecimal characters */ private static final char[] DIGITS_LOWER = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; / * * * is used to establish the output of the hexadecimal character * / private static final char [] DIGITS_UPPER = {' 0 ', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; /** * Converts a byte array to a hexadecimal character array. * * Because two characters are used to represent a byte, the length of the returned char[] will be twice the length of the parameter byte[]. * * @param data * byte[] * @return char containing hexadecimal characters [] */ public static char[] encodeHex(final byte[] data) { return encodeHex(data, true); } /** * Converts a byte array to a hexadecimal character array. * * Because two characters are used to represent a byte, the length of the returned char[] will be twice the length of the parameter byte[]. * * @param data * byte[] * @param toLowerCase * <code>true</code> Convert to lowercase, <code>false</code> Convert to uppercase format * @return contains hexadecimal characters char[] */ public static char[] encodeHex(final byte[] data, final boolean toLowerCase) { return encodeHex(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER); } /** * Converts a byte array to a hexadecimal character array. * * Because two characters are used to represent a byte, the length of the returned char[] will be twice the length of the parameter byte[]. * * @param data * byte[] * @param toDigits * Alphabet for controlling output * @return char containing hexadecimal characters [] */ protected static char[]  encodeHex(final byte[] data, final char[] toDigits) { int l = data.length; char[] out = new char[l << 1]; // two characters form the hex value. for (int i = 0, j = 0; i < l; i++) { out[j++] = toDigits[(0xF0 & data[i]) >>> 4]; out[j++] = toDigits[0x0F & data[i]]; } return out; } /** * Converts a byte array to a hexadecimal string. * * Because two characters are used to represent a byte, the returned string length will be twice the length of the parameter byte[]. * * @param data * byte[] * @return hexadecimal String */ public static String encodeHexStr(final byte[] data) {return encodeHexStr(data, true); } /** * Converts a byte array to a hexadecimal string. * * Because two characters are used to represent a byte, the returned string length will be twice the length of the parameter byte[]. * * @param data * byte[] * @param toLowerCase * <code>true</code> Convert to lowercase, <code>false</code> Convert to uppercase format * @return hexadecimal String */ public static String encodeHexStr(byte[] data, boolean toLowerCase) { return encodeHexStr(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER); } /** * Converts a byte array to a hexadecimal string. * * Because two characters are used to represent a byte, the returned string length will be twice the length of the parameter byte[]. * * @param data * byte[] * @param toDigits * Alphabet used to control output * @return hexadecimal String */ protected static String encodeHexStr(byte[] data, char[] toDigits) { return new String(encodeHex(data, toDigits)); } /** * Converts hexadecimal character array to byte array ** @param data * hexadecimal char[] * @return byte[] * @throws RuntimeException * If the length of the source hexadecimal character array is odd, Will throw a runtime exception */ public static byte[] decodeHex(char[] data) {int len = data.length; if ((len & 0x01) ! = 0) { throw new RuntimeException("Odd number of characters."); } // If a byte corresponds to two hexadecimal characters, set the size of byte[] to half the size of char[]. byte[] out = new byte[len >> 1]; // two characters form the hex value. for (int i = 0, j = 0; j < len; i++) { int f = toDigit(data[j], j) << 4; j++; f = f | toDigit(data[j], j); j++; out[i] = (byte) (f & 0xFF); } return out; } /** * Converts the hexadecimal character to an integer. * * @param ch * Character to be converted to an integer * @param index * character position in the character array * @return an integer * @throws RuntimeException * When ch is not a valid hexadecimal character, Throw this exception */ protected static int toDigit(final char ch, final int index) {final int digit = Character.digit(ch, 16); if (digit == -1) { throw new RuntimeException("Illegal hexadecimal character " + ch + " at index " + index); } return digit; } public static void main(String[] args) { String srcStr = "HelloWorld!" ; String encodeStr = encodeHexStr(srcStr.getBytes(), false); String decodeStr = new String(decodeHex(encodeStr.toCharArray())); System.out.println(" Source string: "+ srcStr); System.out.println(" String encoded in hexadecimal: "+ encodeStr); System.out.println(" hexadecimal decoded to string: "+ decodeStr); }}

Related article

  • Java中的任务调度框架quartz详细解析

    The task scheduling framework in Java is analyzed in detail by quartz

    This article mainly introduces the detailed analysis of the task scheduling framework quartz in Java. Quartz is an open source job scheduling framework written entirely by Java. It provides a simple but powerful mechanism for job scheduling in Java applications
    2023-11-11
  • Java中stream处理中map与flatMap的比较和使用案例

    Comparison and use cases of map and flatMap in stream processing in Java

    This article mainly introduces the comparison and use cases of map and flatMap in stream processing in Java. The article introduces the example code in great detail, which has certain reference value for everyone's study or work. The friends who need to follow the small series to learn together
    2021-03-03
  • JavaWeb实现裁剪图片上传完整代码

    JavaWeb implements crop picture upload complete code

    This article mainly introduces in detail the complete code of javaWeb to achieve clipping image upload, which has a certain reference value, interested partners can refer to it
    2016-09-09
  • mybatis-plus常用注解@TableId和@TableField的用法

    mybatis-plus often annotates @TableId and @TableField usage

    This article mainly introduces the usage of mybatis-plus common annotations @TableId and @TableField. The article introduces it in great detail through example code, which has certain reference value for everyone's study or work. The friends who need it will learn together with Xiaobian below
    2023-04-04
  • Java编程实现计算两个日期的月份差实例代码

    Java programming to calculate the month difference between two dates example code

    This article mainly introduces Java programming to achieve the calculation of two dates of the month difference example code, has a certain reference value, the need of friends can refer to
    2018-01-01
  • jdbc和mybatis的流式查询使用方法

    jdbc and mybatis streaming query usage

    Sometimes the amount of data we need to query is relatively large, but the jvm memory is limited, and the amount of data is too large to cause memory overflow. At this time you can use streaming query, this article mainly introduces jdbc and mybatis streaming query, interested in you can understand
    2021-11-11
  • mybatis-plus的sql加载顺序源码解析

    mybatis-plus sql load sequence source code parsing

    This article mainly introduces the sql loading sequence source code analysis of mybatis plus, friends in need can draw on the reference, I hope to be helpful, I wish you a lot of progress, early promotion and pay rise
    2023-08-08
  • SpringBoot整合java诊断工具Arthas解读

    SpringBoot integrates java diagnostic tool Arthas interpretation

    This article mainly introduces SpringBoot integrated java diagnostic tool Arthas, has a good reference value, I hope to help you. If there are mistakes or incomplete areas, please feel free to comment
    2023-03-03
  • Spring aop+反射实现电话号加密

    Spring aop+ Reflection implements phone number encryption

    The online project involves a large number of query interfaces, and there is a problem that the plaintext display of telephone numbers is not compliant. If the relevant code logic is modified for the phone number related fields in the return result of each interface, the workload is large and the time is long. So the design of phone number encryption annotation, reduce the workload.
    2021-06-06
  • Java模拟HTTP Get Post请求 轻松实现校园BBS自动回帖

    Java simulation HTTP Get Post request easily to achieve campus BBS automatic reply

    This article mainly introduces Java simulation HTTP Get Post request, easy to achieve the campus BBS automatic reply, interested partners can refer to
    2015-12-12

Latest comments