Created
November 6, 2018 04:00
-
-
Save mageddo/20d0b9ffaf135bc245e8d435594d63b6 to your computer and use it in GitHub Desktop.
Byte Array To Hexadecimal
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import java.nio.ByteBuffer; | |
| import java.nio.ByteOrder; | |
| public class Test { | |
| public static void main(String[] args) { | |
| Test t = new Test(); | |
| t.arrayByte2Short(); | |
| t.arrayByte2ShortWay2(); | |
| t.arrayByteReversed2Short(); | |
| t.arrayByteReversed2ShortWay2(); | |
| t.short2HexBytes(); | |
| t.short2HexBytesWay2(); | |
| } | |
| /*** | |
| * Converte o array de bytes para o short | |
| * também poderia ter sido feito com integer, long, etc | |
| */ | |
| public void arrayByte2Short(){ | |
| ByteBuffer bb = ByteBuffer.allocate(2); | |
| bb.put(new byte[]{0x27, 0x0F}); | |
| short shortVal = bb.getShort(0); | |
| System.out.printf("arrayByte2Short: %d\n", shortVal); | |
| } | |
| /*** | |
| * Converte o array de bytes para o short | |
| * também poderia ter sido feito com integer, long, etc | |
| */ | |
| public void arrayByte2ShortWay2(){ | |
| System.out.printf("arrayByte2Short: %d\n", Short.parseShort("270F", 16)); | |
| } | |
| /*** | |
| * Converte o array de bytes para o short<br> | |
| * Ás vezes o array vem inverso na memória, esse método trata isso | |
| * também poderia ter sido feito com integer, long, etc | |
| */ | |
| public void arrayByteReversed2Short(){ | |
| ByteBuffer bb = ByteBuffer.allocate(2); | |
| bb.order(ByteOrder.LITTLE_ENDIAN); | |
| bb.put(new byte[]{0x0F, 0x27}); | |
| short shortVal = bb.getShort(0); | |
| System.out.printf("arrayByteReversed2Short: %d\n", shortVal); | |
| } | |
| /*** | |
| * Converte o array de bytes para o short<br> | |
| * Ás vezes o array vem inverso na memória, esse método trata isso | |
| * também poderia ter sido feito com integer, long, etc | |
| */ | |
| public void arrayByteReversed2ShortWay2(){ | |
| Short s = Short.parseShort("0F27", 16); | |
| Short reversed = Short.reverseBytes(s); | |
| System.out.printf("arrayByteReversed2ShortWay2: %d\n", reversed); | |
| } | |
| /** | |
| * Pega os bytes do número e os mostra | |
| */ | |
| public void short2HexBytes(){ | |
| byte[] bytes = ByteBuffer.allocate(2).putShort((short)9999).array(); | |
| for(byte b: bytes) | |
| System.out.printf("%x ", b); | |
| System.out.println(); | |
| } | |
| /** | |
| * Pega os bytes do número e os mostra | |
| */ | |
| public void short2HexBytesWay2(){ | |
| System.out.printf("short2HexBytes: %s\n", Integer.toHexString(9999)); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment