Java Byte Array Create toBytesWithLength(byte[] buffer, int pos, String string)

Here you can find the source of toBytesWithLength(byte[] buffer, int pos, String string)

Description

to Bytes With Length

License

Apache License

Declaration

public static int toBytesWithLength(byte[] buffer, int pos, String string) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

public class Main {
    public static int toBytesWithLength(byte[] buffer, int pos, String string) {
        byte[] strBytes = string.getBytes();
        if (strBytes.length > 32767) {
            throw new RuntimeException("Payload is too long; " + strBytes.length);
        }/*from w w  w . j  a  va2  s.c  o m*/
        buffer[pos] = (byte) (strBytes.length / 256);
        buffer[pos + 1] = (byte) (strBytes.length & 255);
        System.arraycopy(strBytes, 0, buffer, pos + 2, strBytes.length);
        return pos + strBytes.length + 2;
    }

    public static int toBytesWithLength(byte[] buffer, int pos, byte[] bytes) {
        if (bytes.length > 32767) {
            throw new RuntimeException("Payload is too long; " + bytes.length);
        }
        buffer[pos] = (byte) (bytes.length / 256);
        buffer[pos + 1] = (byte) (bytes.length & 255);
        System.arraycopy(bytes, 0, buffer, pos + 2, bytes.length);
        return pos + bytes.length + 2;
    }
}

Related

  1. toBytesString(byte[] bytes)
  2. toByteString(byte[] bytes, String seperator)
  3. toByteString(byte[] content, int len)
  4. toByteString(final byte[] b)
  5. toByteString(final String source)
  6. toBytesWithLengthLong(byte[] buffer, int pos, byte[] bytes)