Created
May 30, 2017 17:28
-
-
Save b-studios/aeddffa5646e3a9e2d8af6fae8ff42fc to your computer and use it in GitHub Desktop.
Short example demonstrating how to read from a java.nio.ByteBuffer
This file contains 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.util.Arrays; | |
class Header { | |
private final Short framesize; | |
public Header(short framesize) { | |
this(new Short(framesize)); | |
} | |
public Header(Short framesize) { | |
this.framesize = framesize; | |
} | |
@Override | |
public String toString() { | |
return "Header(" + framesize.toString() + ")"; | |
} | |
public Short getFramesize() { | |
return framesize; | |
} | |
} | |
public class Example { | |
static byte[] sampleFrame() { | |
String header = "AA 01 00 34 1E 36 44 85 36 00 00 00 41 B1"; | |
String stat = "00 00"; | |
// TODO currently in 16bit integer, change to float! | |
String phasors = "39 2B 00 00 E3 6A CE 7C E3 6A 31 83 04 44 00 00"; | |
String freq = "09 C4"; | |
String dfreq = "00 00"; | |
String analog = "42 C8 00 00 44 7A 00 00 46 1C 40 00"; | |
String digital = "3C 12"; | |
String crc = "D4 3F"; | |
return hexToByte(header + stat + phasors + freq + dfreq + analog + digital + crc); | |
} | |
public static void main(String[] args) { | |
System.out.println(readHeader(ByteBuffer.wrap(sampleFrame()))); | |
} | |
private static Header readHeader(ByteBuffer buffer) { | |
// check sync bytes | |
byte[] sync = new byte[2]; | |
buffer.get(sync, 0, 2); | |
assertEquals(sync, "AA01"); | |
// read framesize | |
short framesize = buffer.getShort(); | |
// ignore next 10 bytes | |
buffer.position(buffer.position() + 10); | |
return new Header(framesize); | |
} | |
private static void assertEquals(byte[] got, String expected) { | |
if (!Arrays.equals(got, hexToByte(expected))) { | |
throw new RuntimeException("byte sequences don't match"); | |
} | |
} | |
// copied and adopted from answer in | |
// https://stackoverflow.com/questions/140131/convert-a-string-representation-of-a-hex-dump-to-a-byte-array-using-java | |
// | |
// alternatively use apache commons codec: http://commons.apache.org/proper/commons-codec/ | |
private static byte[] hexToByte(String hex) { | |
String noSpace = hex.replaceAll("\\s+", ""); | |
int len = noSpace.length(); | |
byte[] data = new byte[len / 2]; | |
for (int i = 0; i < len; i += 2) { | |
data[i / 2] = (byte) ((Character.digit(noSpace.charAt(i), 16) << 4) | |
+ Character.digit(noSpace.charAt(i + 1), 16)); | |
} | |
return data; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment