Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read data from ByteBuffer

How to read the data stored in ByteBuffer?

  • setValue() - gets value "12 10" and is converted into Hexadecimal value and is stored in String[] data.
  • write() - converts data into bytes and stores in ByteBuffer dest.
  • readBuffer - How can I read data from ByteBuffer?
static String[] data = {};
//value = "12 10";
String setValue(String value) {
    String[] samples = value.split("[ ,\n]+");
    data = new String[samples.length];

    //Generates Hex values
    for (int i = 0; i < samples.length; i++) {
        samples[i] = "0x"+String.format("%02x", Byte.parseByte(samples[i]));
    //data[i] will have values 0x0c, 0x0a
        data[i] = samples[i];
    }
    System.out.println("data :: " +Arrays.toString(samples));
    return value;
}


void write(int sequenceNumber, ByteBuffer dest) {
        for (int i = 0; i < data.length; i++) {
            System.out.println("data[i] in bytes :: "+data[i].getBytes());

            dest.put(data[i].getBytes());           

        }   

    }   

void readBuffer(ByteBuffer destValue)
{
        //How to read the data stored in ByteBuffer?
}
like image 895
sanam_bl Avatar asked Oct 28 '25 13:10

sanam_bl


2 Answers

destValue.rewind() 
while (destValue.hasRemaining())
     System.out.println((char)destValue.get());
}
like image 65
Sarit Adhikari Avatar answered Oct 31 '25 11:10

Sarit Adhikari


You can get the backing array of a ByteBuffer with .array(). If you want to convert it to a String, you'll also need to get the current position, or else you will have a lot of zero-bytes at the end. So you'll end up with code like:

new String(buf.array(), 0, buf.position())

Edit: Oh, it appears you want the byte values. Those you could either get by calling Arrays.toString(Arrays.copyOf(buf.array(), 0, buf.position()) or loop x from 0 to buf.position calling Integer.toString((int)buf.get(x) & 0xFF, 16) (to get a 2-digit hex code) and collecting the results in a StringBuilder.

like image 39
llogiq Avatar answered Oct 31 '25 10:10

llogiq



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!