Skip to content

BytesUtils

Julien Millau edited this page Jul 14, 2014 · 8 revisions

This class provided static methods to convert byte array to String, String to byte array, int to byte array, byte array to binary representation.

Convert byte array to String

    byte[] array = new byte[]{0x00,0x30,0x40};

    System.out.println(BytesUtils.bytesToString(array));
    // display "00 30 40" (with space)

    System.out.println(BytesUtils.bytesToStringNoSpace(array));
    // display "003040" (without space)

    System.out.println(BytesUtils.bytesToString(array));
    // display "3040" (Remove left 0 bytes)

Convert String to byte array
Each byte must have two hex digits.

    String bytes = "04 12 34";
    byte[] array = BytesUtils.fromString(bytes);
    // Return new byte[]{0x04,0x12,0x34}

Convert Int/Integer to byte array
Return an array of 4 bytes

    int val = 1;
    byte[] array = BytesUtils.toByteArray(val); // return [0x00,0x00,0x00,0x01]

Convert byte array to int

    byte[] array = new byte[]{0x01,0x00};
    int val = BytesUtils.byteArrayToInt(array); // return 256
    int val = BytesUtils.byteArrayToInt(array,0,1); // return 1  

Set a bit of a byte to 1 or 0

    byte data = 0x0F;
    BytesUtils.setBit(data,0,false); // return 00001110b or 0x0E
    BytesUtils.setBit(data,4,true); // return 00011111b or 0x1F

Check if bit at specified index is set to 1

    BytesUtils.matchBitByBitIndex(1,0); // return true
    BytesUtils.matchBitByBitIndex(256,8); // return true
    BytesUtils.matchBitByBitIndex(256,7); // return false
Clone this wiki locally