Existem muitas maneiras de converter o sistema binário em Java. Entre eles, existem aulas de embalagem para hexadecimal decimal binário básico básico, etc., que não precisam ser implementadas por meio de algoritmos de dois saídas. Os detalhes são os seguintes:
Primeiro de tudo, os métodos de conversão binária mais simples são:
Converter decimal em hexadecimal:
String integer.tohexstring (int i)
Converter decimal para octal
String integer.tooctalstring (int i)
Converter decimal em binário
String Integer.TobinaryString (int i)
Converter hexadecimal em decimal
Integer.ValueOf ("ffff", 16) .ToString () // não pode lidar com o prefixo 0x
Converter octal a decimal
Integer.ValueOf ("76", 8) .ToString () // Prefixo 0 pode ser processado para ser binário para decimal
Integer.ValueOf ("0101", 2) .ToString ()
Existe alguma maneira de converter diretamente 2, 8, hexadecimal em decimal?
Java.lang.Integer Class
parseint (string s, int radix)
Use a cardinalidade especificada pelo segundo parâmetro para analisar o parâmetro String em um número inteiro assinado.
Exemplos do JDK:
parseint ("0", 10) retorna 0
Parseint ("473", 10) retorna 473
parseint ("-0", 10) retorna 0
parseint (" -ff", 16) retorna -255
Parseint ("1100110", 2) retorna 102
Parseint ("2147483647", 10) retorna 2147483647
parseint (" -2147483648", 10) retorna -2147483648
Parseint ("2147483648", 10) Throwsa NumberFormatexception
Parseint ("99", Throwsa NumberFormatexception
Parseint ("Kona", 10) Throwsa NumberFormatexception
Parseint ("Kona", 27) retorna 411787
Como escrever uma conversão binária (dois, oito, dezesseis) sem algoritmo
Integer.TobinaryString
Integer.tooctaltring
Integer.ToHexString
Em seguida, apresente a conversão de byte e números hexadecimais em Java
Análise de princípios:
O byte em Java é composto por 8 bits, e o hexadecimal é o estado em 16, que é representado por 4 bits porque 24 = 16. Assim, podemos converter um byte em dois caracteres hexadecimais, ou seja, converter os 4 dígitos altos e baixos em caracteres hexadecimais correspondentes e combinar essas duas cordas hexadecimais para obter a corda hexadecimal de byte. Da mesma forma, a conversão oposta também converte dois caracteres hexadecimais em um byte.
Em Java, existem duas idéias principais para converter bytes e hexadecimal:
1. Quando o byte binário é convertido em hexadecimal, execute a operação "&" do byte alta e 0xf0 e depois desligue a esquerda por 4 bits para obter o hexadecimal a da alta de byte; Execute a operação "&" do byte baixo e 0x0f para obter o b -dígito hexadecimal do baixo e os dígitos e montar dois números hexadecimais em um pedaço de AB, que é a representação hexadecimal do byte.
2. Quando hexadecimal a bytes binários, mova o número decimal correspondente ao caráter hexadecimal para a direita 4 para obter o byte alto a; Faça o "|" operação do número decimal B e A do caráter hexadecimal correspondente ao byte baixo para obter a representação de bytes binários hexadecimais
Uma das funções de conversão é a seguinte:
/** * * @param bytes * @return Converte o binário para o caractere hexadecimal Saída */</span> String estática privada hexstr = "0123456789ABCDef"; // global public static string binaryToHexString (byte [] bytes) {string result = ""; String hex = ""; for (int i = 0; i <bytes.length; i ++) {// bytes são 4 bits mais altos <strong> hex = string.valueof (hexstr.charat ((bytes [i] & 0xf0) >> 4)); </strong> // bytes são 4 bits mais baixos <strong> hex += string.valueof (hexstr.charat (bytes [i] e 0x0f)); </strong> resultado += hexadecimal; } resultado de retorno; }/** * * @param hexstring * @return converte hexadecimal to byte matriz */public static byte [] hexstringTobinary (string hexstring) {// O comprimento da hexstring é arredondado por 2, como o comprimento de bytes int len = hexstring.lngen)/2; byte [] bytes = novo byte [len]; byte high = 0; // O byte de alto bit de quatro bits baixo = 0; // o byte baixo de quatro bits para (int i = 0; i <len; i ++) {// transfira para os quatro bits certos para obter o alto bit alto = (byte) ((hexstr.indexof (hexstring.charat (2*)) <l); baixo = (byte) hexstr.indexof (hexstring.charat (2*i+1)); bytes [i] = (byte) (alto | baixo); // status ou operação alta} retorna bytes; }} Há também um método semelhante:
<span style = "font-size: 14px;">* converta byte [] em string hexadecimal. Aqui podemos converter byte em int e depois usar o número inteiro.tohexstring (int) para converter em string hexadecimal.
* @param src byte [] data * @return hex string */ public static string bytestoHexString (byte [] src) {stringbuilder stringbuilder = new StringBuilder (""); if (src == null || src.length <= 0) {return null; } para (int i = 0; i <src.length; i ++) {int v = src [i] & 0xff; String hv = integer.tohexString (v); if (hv.length () <2) {stringbuilder.append (0); } stringbuilder.append (hv); } return stringbuilder.toString (); } / ** * Converta a string hexadecimal em byte [] * @param hexstring o string hexépaco * @return byte [] * / public static byte [] hexstringTobytes (string hexstring) {if (hexstring == null || hexstring.equals (")) {return null; } hexstring = hexstring.touppercase (); int length = hexstring.length () / 2; char [] hexchars = hexstring.toCharArray (); byte [] d = novo byte [comprimento]; for (int i = 0; i <comprimento; i ++) {int pos = i * 2; d [i] = (byte) (ChartObyte (HexChars [POS]) << 4 | ChartObyte (HexChars [POS + 1])); } retornar d; } / ** * Converta char em byte * @param c char * @return byte * / byte privado ChartObyte (char c) {return (byte) "0123456789abcdef" .IndexOf (c); } </span>Os dois métodos são semelhantes, observe aqui
O acima é uma string que converte byte [] em hexadecimal. Observe que B [i] e 0xff executa um cálculo de um byte e 0xff e, em seguida, usa o número inteiro.tohexstring para obter a sequência hexadecimal. Você pode ver isso
B [i] e 0XFF Operação ainda é um INT, então por que você precisa executar uma operação int com 0xFF? Inteiro direto.tohexstring (b [i]);, não pode forçar o byte a ser convertido? A resposta é não.
A razão é:
1. O tamanho do byte é de 8 bits e o tamanho de int é de 32 bits
2. O sistema de duas partes de Java usa complemento
Portanto, quando números negativos são e com números negativos, os números negativos preencherão automaticamente 1, o que levará a erros
O 0XFF é uma cirurgia plástica por padrão; portanto, quando um byte e 0xFF estiverem envolvidos, o byte será convertido em uma operação de cirurgia plástica primeiro, para que os 24 bits altos no resultado sejam sempre limpos em 0, então o resultado é sempre o que queremos.
Existem alguns métodos de resumo online:
Converta String para o método hexadecimal string 1:
/ *** Converta a string em string hexadecimal*/ public static string str2hexstr (string str) {char [] chars = "0123456789abcdef" .toCharArray (); Stringbuilder sb = new stringbuilder (""); byte [] bs = str.getBytes (); int bit; for (int i = 0; i <bs.length; i ++) {bit = (bs [i] & 0x0f0) >> 4; sb.append (chars [bit]); bit = bs [i] e 0x0f; sb.append (chars [bit]); } return sb.toString (); }Converter string hexadecimal em Método da Array 1:
/ ** * Converta hexstring em matriz de bytes * @param hexstring * @return byte [] * / public static byte [] hexstringTobyte (string hex) {int len = (hex.length () / 2); byte [] resultado = novo byte [len]; char [] achar = hex.toCharArray (); for (int i = 0; i <len; i ++) {int pos = i * 2; resultado [i] = (byte) (Tobyte (achar [pos]) << 4 | Tobyte (achar [pos + 1])); } resultado de retorno; } private static int tobyte (char c) {byte b = (byte) "0123456789abcdef" .IndexOf (c); retornar b; }Converta a matriz para o método hexadecimal string 1:
/ ** * Converta a matriz em string hexadecimal * @param byte [] * @return hexstring */ public static final string bytestoHexString (byte [] barray) {stringbuffer sb = new stringbuffer (barray.length); String Stemp; for (int i = 0; i <barray.length; i ++) {stemp = Integer.toHexString (0xff & barray [i]); if (stemp.length () <2) sb.append (0); sb.append (stemp.touppercase ()); } return sb.toString (); }Método 2 de converter a matriz de byte [] em string hexadecimal:
/ ** * Converta a matriz em string hexadecimal * @param byte [] * @return hexstring */ public static string tohexstring1 (byte [] b) {stringBuffer buffer = new StringBuffer (); for (int i = 0; i <b.Length; ++ i) {buffer.append (tohexString1 (b [i])); } retornar buffer.toString (); } public static string toHexString1 (byte b) {string s = Integer.toHexString (b & 0xff); if (s.Length () == 1) {return "0" + s; } else {return s; }}Método 1 da sequência de conversão de string hexadecimal:
/ ** * Converta hexstring em string * @param hexstring * @return string */ public static string hexstr2str (string hexstr) {string str = "0123456789abcdef"; char [] hexs = hexst.toCharArray (); byte [] bytes = novo byte [hexstr.length () / 2]; int n; for (int i = 0; i <bytes.length; i ++) {n = str.indexOf (hexds [2 * i]) * 16; n + = str.indexOf (hexésimo [2 * i + 1]); bytes [i] = (byte) (n & 0xff); } retornar nova string (bytes); }Método 2 de conversão de cordas em cordas hexadecimais:
/ ** * Hexstring convert String * @param hexstring * @return string * / public static string tostringhex (string s) {byte [] Bakeyword = new Byte [s.Length () / 2]; for (int i = 0; i <Bakeyword.length; i ++) {try {Bakeyword [i] = (byte) (0xff & integer.parseint (s.substring (i * 2, i * 2+2), 16)); } catch (Exceção e) {e.printStackTrace (); }} tente {s = new String (Bakeyword, "utf-8"); // utf-16le: não} catch (Exceção E1) {e1.printStackTrace (); } retornar s; }O artigo acima sobre a conversão de Java, o método de conversão de byte e hexadecimal é todo o conteúdo que compartilho com você. Espero que você possa lhe dar uma referência e espero que você possa apoiar mais o wulin.com.