Este artículo describe la implementación de Java de la clase de herramienta de conversión binaria. Compártelo para su referencia, como sigue:
import java.nio.charset.charset;/*** hexadecimal (abreviado como hex o subíndice 16) es un sistema de transporte en matemáticas que va de 16 a 1. Generalmente está representado por los números 0 a 9 y las letras A a F (donde: a ~ f es 10 ~ 15). <br> * Por ejemplo, el número decimal 57 está escrito en binario 111001 y el hexadecimal 39 está escrito en hexadecimal. <br> * Para distinguir entre los valores hexadecimales y decimales, los idiomas como Java y C prefijo 0x frente al número hexadecimal, por ejemplo, 0x20 es 32 en decimal, en lugar de 20 en decimal <br> * * referencia: https://my.oschina.net/xinxingeGeya/2874 * @authps. Looly * */public class hexkit {/** * Matriz de caracteres minúsculas utilizada para crear la salida de caracteres hexadecimales */private static final char [] digits_lower = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'D', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ','. }; / *** Una matriz de caracteres de capital utilizada para crear la salida de caracteres hexadecimales*/ private static final char [] digits_upper = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e'}; // ------------------------------------------------------------------------------------------------------------------------------------------------------- * @return hex char [] */ public static char [] encodeHex (byte [] data) {return encodeHex (data, true); } / *** Convierta una matriz de bytes a una matriz de caracteres hexadecimal** @param str string* @param encoding* @return hex char []* / public static char [] encodeHex (string str, charset charset) {return encodeHex (strkit.getbytes (str, charset), verdadero); }/** * Convertir la matriz de bytes a la matriz de caracteres hexadecimal * * @param data byte [] * @param tolowercase <code> true </code> transferir al formato minúscula, <code> false </code> transferir a UpperCase Format * @return hex Char [] */public Char [] CharrodeHex (byte [] Datos, boolean Tolower) tolowercase? } / ** * Convertir la matriz de byte a cadena hexadecimal * * @param data byte [] * @return hexstring * / public static string codeDhexstr (byte [] data) {return codexstr (data, true); }/** * Convertir la matriz de bytes a cadena hex * * @param data byte [] * @param tolowercase <code> true </code> transferir a formato minúscula, <code> false </code> transferir a formato uppercase * @return hexString */public static string codeDeDexstr (byte [] data, booleanean toLowercase) {returnHeDeDeDeDeDeDeDexString (data, tolwerScase, toloL Digits_lower: digits_upper); } // --------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------- decodeHexstr (hexstr.toCarArray (), charset); } / *** Convierta la matriz de caracteres Hex en cadena** @param hexdata hex char []* @param encoding* @return string* / public static string decodeHexstr (char [] hexData, charset charset) {return strkit.str (decodeHex (hexdata), charset); } / ** * Convierta la matriz de caracteres Hex en la matriz de bytes * * @param hexData hex char [] * @return byte [] * @throws runtimeException Si la matriz de caracteres hex de origen es una longitud extraña, se lanzará una excepción de tiempo de ejecución * / public static byte [] decodehex (char [] hexdata) {int len = hexdata.l longitud; if ((len & 0x01)! = 0) {tire nueva runtimeException ("número impar de caracteres"); } byte [] out = new Byte [len >> 1]; // Dos caracteres forman el valor hexadecimal. for (int i = 0, j = 0; j <len; i ++) {int f = toDigit (hexData [j], j) << 4; j ++; F = F | Todigit (hexdata [j], j); j ++; out [i] = (byte) (f & 0xff); } regresar; } // ------------------------------------------------------------------------------------------------------------------------------------------------------- Todigits) {return new String (encodeHex (data, Todigits)); } / ** * Convierta la matriz de bytes a la matriz de caracteres hex * * @param data byte [] * @param Todigits char [] para controlar la salida * @return hex char [] * / private static char [] codex (byte [] data, char [] Todigits) {int l = data.length; char [] out = new Char [l << 1]; // Dos caracteres forman el valor hexadecimal. for (int i = 0, j = 0; i <l; i ++) {out [j ++] = Todigits [(0xf0 & data [i]) >>> 4]; out [j ++] = Todigits [0x0f & data [i]]; } regresar; } / *** Convierta los caracteres hexadecimales en un entero*** @param ch hexadecimal char* @param index la posición de los caracteres hexadecimales en la matriz de caracteres* @return un entero* @throws runtimeException cuando el CH no es una característica hexadecimal legal, tirar una excepción de tiempo de ejecución* / private intit digit (int char ch, int cheCh, int digit) Personaje. Digit (CH, 16); if (digit == -1) {lanzar nueva runtimeException ("carácter hexadecimal ilegal" + ch + "en índice" + index); } DIGIT DE RETURN; } // --------------------------------------------------------------------------------------------------------------------------------------------------- bstring.length () % 8! = 0) return null; StringBuffer tmp = new StringBuffer (); int itmp = 0; for (int i = 0; i <bstring.length (); i += 4) {itmp = 0; for (int j = 0; j <4; j ++) {itmp + = integer.parseInt (bstring.substring (i + j, i + j + 1)) << (4 - j - 1); } tmp.append (integer.tohexString (itmp)); } return tmp.ToString (); } / ** * hexstring * @param hexstring * @return * / public static string hex2binary (string hexstring) {if (hexString == null || hexString.length () % 2! = 0) return null; Cadena bString = "", tmp; for (int i = 0; i <hexString.length (); i ++) {tmp = "0000" + integer.tobinaryString (integer.parseInt (hexstring.substring (i, i + 1), 16)); bstring += tmp.substring (tmp.length () - 4); } return bString; } / ** * Convierta binario a hex * @param buf * @return * / public static string binary2Hex (byte buf []) {stringBuffer sb = new StringBuffer (); for (int i = 0; i <buf.length; i ++) {string hex = integer.tohexString (buf [i] & 0xff); if (hex.length () == 1) {hex = '0' + hex; } sb.append (hex.touppercase ()); } return sb.ToString (); } / ** * Convierta hexstr a binario * @param hexstr * @return * / public static byte [] hex2byte (string hexstr) {if (hexstr.length () <1) return null; byte [] resultado = nuevo byte [hexstr.length () / 2]; for (int i = 0; i <hexstr.length () / 2; i ++) {int high = integer.ParseInt (hexstr.substring (i * 2, i * 2+1), 16); int low = Integer.ParseInt (hexstr.substring (i * 2 + 1, i * 2 + 2), 16); resultado [i] = (byte) (alto * 16 + bajo); } resultado de retorno; }}PD: Aquí hay algunas herramientas de conversión y cálculo en línea para este sitio web. Creo que te será útil:
Herramienta de conversión arbitraria en línea:
http://tools.vevb.com/transcoding/hexconvert
Calculadora estándar en línea:
http://tools.vevb.com/jisuanqi/jsq
Calculadora científica en línea:
http://tools.vevb.com/jisuanqi/jsqkeexue
Para obtener más información sobre los algoritmos de Java, los lectores interesados en este sitio pueden ver los temas: "Estructura de datos Java y tutorial de algoritmo", "Resumen de las puntas de nodo de operación de Java DOM", "Resumen de Java Archivo y TIPS de operación de directorio" y "Summary of Java Cache Operation Tips" TIPS ""
Espero que este artículo sea útil para la programación Java de todos.