Converter dados hexadecimal para string

2 respostas
J

Olá galera, será que alguém pode me ajudar com um código…trabalho com desenvolvimento de app para leitores de RFID, para gravar dados uso um método que converte uma string em um vetor de byte para hexadecimal, até ai tudo bem, mas o retorno não esta sendo uma string, ou seja, o método que converte o vetor byte de hexadecimal para string não funciona
Vou postar aqui os dois métodos

private static byte[] hexStringToByteArray(String s) {
		int len = s.length();

		byte[] data = new byte[len / 2];
		for (int i = 0; i < len; i += 2) {
			data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16));
		}
		return data;
	}


private static String byteArrayToHexString(byte[] b) {
		StringBuffer sb = new StringBuffer(b.length * 2);
		for (int i = 0; i < b.length; i++) {
			int v = b[i] & 0xff;
			if (v < 16) {
				sb.append('0');
			}
			sb.append(Integer.toHexString(v));
		}
		return sb.toString().toUpperCase();
	}

Esses são os dois métodos usados, lembrando que, para gravar é um sucesso mas o retorno continua sendo em hexadecimal
Fico grato por qualquer ajuda
Obrigado

2 Respostas

tondatto
static String byteArrayToHexString(byte in[]) {

                byte ch = 0x00;
                int i = 0;
                if (in == null || in.length <= 0)
                        return null;

                String pseudo[] = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
                                "A", "B", "C", "D", "E", "F" };
                StringBuffer out = new StringBuffer(in.length * 2);

                while (i < in.length) {
                        ch = (byte) (in[i] & 0xF0); // Strip offhigh nibble
                        ch = (byte) (ch >>> 4);
                        // shift the bits down
                        ch = (byte) (ch & 0x0F);
                        // must do this is high order bit is on!
                        out.append(pseudo[ch]); // convert thenibble to a String
                        // Character
                        ch = (byte) (in[i] & 0x0F); // Strip off low nibble
                        out.append(pseudo[ch]); // convert the nibble to a String
                        // Character
                        i++;
                }
                String rslt = new String(out);
                return rslt;
        }

Fonte: [url]http://code.google.com/p/javaspoon/source/browse/trunk/de.xam.devtools15/src/main/java/de/xam/devtools/ByteArrayToHexString.java[/url]

J

Valeu pelo código tondatto, mas ainda continua imprimindo em hexadecimal…tô passando uma string “joserenato” no primeiro método eu gravo assim: [B@190d11 em seguida com o método que eu já tinha e até mesmo esse que você me passou ainda continua me retornando em hexadecimal: EFFEFEFAEF

O que eu faço, tem alguma outra sugestão ?

Obrigado !

Criado 22 de novembro de 2012
Ultima resposta 23 de nov. de 2012
Respostas 2
Participantes 2