Este artigo descreve a implementação Java da classe de ferramentas de conversão binária. Compartilhe -o para sua referência, como segue:
importar java.nio.charset.charset;/*** hexadecimal (abreviado como hexadecimal ou subscrito 16) é um sistema de transporte em matemática que vai de 16 a 1. É geralmente representado pelos números de 0 a 9 e as letras a a f (onde: a ~ f é 10 ~ 15). <br> * Por exemplo, o número decimal 57 está escrito em 111001 binário e o hexadecimal 39 é escrito em hexadecimal. <br> * In order to distinguish between hexadecimal and decimal values, languages like java and c will prefix 0x in front of the hexadecimal number, for example, 0x20 is 32 in decimal, instead of 20 in decimal<br> * * Reference: https://my.oschina.net/xinxingegeya/blog/287476 * * @author Looly * */public class HexKit { /** * Lowercase character array 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' }; /** * A capital character array used to create the output of hexadecimal characters*/ private static final char[] DIGITS_UPPER = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; //-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------TeTer [Juster [---TeTer [----------------------------------------------------------------------------- * @return hexh char [] */ public static char [] codehex (byte [] data) {return codeHex (dados, true); } / *** Converta uma matriz de bytes em uma matriz hexadecimal de caracteres** @param str string* @param charset codificação* @return hex char []* / public static char [] EncodeHex (strt str, charset) {return codeHex (strkit.getBytes (str Charset); }/** * Converta a matriz de bytes em matriz de caracteres hexadecimais * * @param dados byte [] * @Param TolowerCase <Code> true </code> transferir para o formato minúsculo, <code> false </code> transferir para o uppercase format * @return hex char [] */public static share [] codehex (bytes [] Datas [] @return hex char [] */public static share [] tolhex (bytes [] dados [] bels, bys), bels), beliStAn (), que vasta (codexe) (codewer) (code) ? } / ** * Converta a matriz de byte em string hexadecimal * * @param dados byte [] * @return hexstring * / public static string codeHexstr (byte [] data) {return codeHexstr (dados, true); }/** * Converta a matriz de byte em string hexadecimal * * @param dados byte [] * @param tolowerCase <code> true </code> transferir para o formato minúsculo, <code> false </code> transferir para uppercase formato * @return hexstring */public strath strathexstr (byString (] tonConean, boolean tolean, booleanClower) Digits_upper); } // --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- decodehexstr (hexstr.toCharArray (), charset); } / *** Converta a matriz de caracteres hexadecimal em string** @param hexdata hexé -char []* @param charset Encoding* @return string* / public static string decodeHexstr (char [] hexdata, charset strkit) {return strkit.str (decodehex (hexdata), charset); } / ** * Converta a matriz de caracteres hexadecimal em matriz de bytes * * @param hexdata hex hex char [] * @return byte [] * @throws RunTimeException Se a matriz de caracteres hexadecimal de origem for um comprimento estranho, uma exceção de tempo de execução será atirada * / public static byte [] decodehex (char [] hexdata). if ((len & 0x01)! = 0) {Throw New RunTimeException ("Número ímpar de caracteres."); } byte [] out = novo byte [len >> 1]; // Dois caracteres formam o 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); } retornar; } //------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Todigits) {return New String (EncodeHex (dados, Todigits)); } / ** * Converta a matriz de bytes em matriz de caracteres hexadecimal * * @param dados byte [] * @param Todigits char [] para controlar a saída * @return hexé char [] out = novo char [l << 1]; // Dois caracteres formam o valor hexadecimal. para (int i = 0, j = 0; i <l; i ++) {out [j ++] = Todigits [(0xf0 & dados [i]) >>> 4]; out [j ++] = Todigits [0x0f & dados [i]]; } retornar; } / *** Converta caracteres hexadecimais em um número inteiro** @param ch hexadecimal char* @param índice a posição dos caracteres hexadecimais na matriz de caracteres* @return a integração* @Throws RuntimeException Quando Chring não é um caráter legal (ex -RunTime)* / privado {) /) @Th) / privattTent Inttaty quando Chring), quando Cher), que é uma exceção de runção @) / privatt Inttation INTTIG INT -DIGT INTTAT INTTAT INTTAT INTST INTTAT INTT INTTAT INTT para Caractere.digit (CH, 16); if (digit == -1) {lança nova RunTimeException ("caractere hexadecimal ilegal" + ch + "no índice" + índice); } retornar dígito; } //----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- BString.Length () % 8! = 0) retorna nulo; 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)); } retornar tmp.toString (); } / ** * hexstring * @param hexstring * @return * / public static string hex2binary (string hexstring) {if (hexstring == null || hexstring.length () % 2! = 0) return null; String 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); } retornar BString; } / ** * converta binário para hexadecimal * @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] e 0xff); if (hex.Length () == 1) {hex = '0' + hex; } sb.append (hex.touppercase ()); } return sb.toString (); } / ** * Converta hexstr em binário * @param hexstr * @return * / public static byte [] hex2byte (string hexstr) {if (hexstr.length () <1) return null; byte [] resultado = novo 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 + baixo); } resultado de retorno; }}PS: Aqui estão algumas ferramentas de conversão e cálculo on -line para este site. Eu acredito que será útil para você:
Ferramenta de conversão arbitrária online:
http://tools.vevb.com/transcoding/hexconvert
Calculadora Standard Online:
http://tools.vevb.com/jisuanqi/jsq
Calculadora científica online:
http://tools.vevb.com/jisuanqi/jsqkeexue
Para obter mais informações sobre os algoritmos Java, os leitores interessados neste site podem visualizar os tópicos: "Estrutura de dados Java e tutorial de algoritmo", "Resumo das dicas de nó da operação Java Dom", "Resumo de dicas de operação de Java e Operação de Java" e "Resumo de Java cache" Tips "TIPS"
Espero que este artigo seja útil para a programação Java de todos.