Java Code Examples for java.nio.ByteBuffer#array()

The following examples show how to use java.nio.ByteBuffer#array() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AreaTest.java    From geonetworking with Apache License 2.0 6 votes vote down vote up
private void verifyAreaRectangleBytes(Area rectangle, Position center, int distanceA,
                                      int distanceB, int degrees) {
  ByteBuffer actualByteBuffer = getAreaByteBuffer();
  rectangle.putTo(actualByteBuffer);

  byte[] actual = actualByteBuffer.array();
  byte[] expected = areaParamToBytes(center, distanceA, distanceB, degrees);
  if (LOGGING) {
    System.out.println("Expected:");
    asBinaryString(expected);
    System.out.println("Actual:");
    asBinaryString(actual);
  }

  assertArrayEquals(expected, actual);

  Area actualArea = Area.getFrom(ByteBuffer.wrap(expected), Area.Type.RECTANGLE);
  assertEquals(rectangle, actualArea);
}
 
Example 2
Source File: Dhcp6IaNaOption.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
public byte[] serialize() {
    int payloadLen = DEFAULT_LEN + options.stream()
            .mapToInt(opt -> (int) opt.getLength() + Dhcp6Option.DEFAULT_LEN)
            .sum();
    int len = Dhcp6Option.DEFAULT_LEN + payloadLen;
    ByteBuffer bb = ByteBuffer.allocate(len);
    bb.putShort(DHCP6.OptionCode.IA_NA.value());
    bb.putShort((short) payloadLen);
    bb.putInt(iaId);
    bb.putInt(t1);
    bb.putInt(t2);

    options.stream().map(Dhcp6Option::serialize).forEach(bb::put);
    return bb.array();
}
 
Example 3
Source File: ChannelTest.java    From yajsync with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testTransferString() throws ChannelException
{
    Environment.setAllocateDirect(false);

    ByteBuffer wb = ByteBuffer.allocate(32);
    WritableByteBufferChannel w = new WritableByteBufferChannel(wb);
    RsyncOutChannel _out = new RsyncOutChannel(w);

    String testString = "abcdefghijklm ö\\";
    _out.put(ByteBuffer.wrap(testString.getBytes()));
    _out.flush();
    assertTrue(wb.position() > 0);

    wb.flip();
    ReadableByteChannel r = new ReadableByteBufferChannel(wb);
    RsyncInChannel _in = new RsyncInChannel(r, this);

    ByteBuffer res = _in.get(testString.getBytes().length);
    assertTrue(wb.position() > 0);
    assertTrue(res.position() == 0);

    String resultString = new String(res.array(), 0, res.remaining());
    assertEquals(testString, resultString);
}
 
Example 4
Source File: TextIndexBunchedSerializer.java    From fdb-record-layer with Apache License 2.0 6 votes vote down vote up
/**
 * Packs a key and value into a byte array. This will write out the tuple and
 * position list in a way consistent with the way each entry is serialized by
 * {@link #serializeEntries(List)}. Because this serializer supports appending,
 * one can take the output of this function and append it to the end of an
 * already serialized entry list to produce the serialized form of that list
 * with this entry appended to the end.
 *
 * @param key the key of the map entry
 * @param value the value of the map entry
 * @return the serialized map entry
 * @throws BunchedSerializationException if the value is not monotonically increasing
 *                                       non-negative integers or if packing the tuple fails
 */
@Nonnull
@Override
public byte[] serializeEntry(@Nonnull Tuple key, @Nonnull List<Integer> value) {
    try {
        byte[] serializedKey = key.pack();
        int listSize = getListSize(value);
        int size = getVarIntSize(serializedKey.length) + serializedKey.length + getVarIntSize(listSize) + listSize;
        ByteBuffer buffer = ByteBuffer.allocate(size);
        serializeVarInt(buffer, serializedKey.length);
        buffer.put(serializedKey);
        serializeList(buffer, value, listSize);
        return buffer.array();
    } catch (RuntimeException e) {
        throw new BunchedSerializationException("unable to serialize entry", e)
                .setValue(new AbstractMap.SimpleImmutableEntry<>(key, value));
    }
}
 
Example 5
Source File: SQLiteBlobHelper.java    From libcommon with Apache License 2.0 6 votes vote down vote up
/**
 * double[]をbyte[]に変換して返す
 *
 * @param array
 * @param offset
 * @param num
 * @return
 */
public static byte[] intArrayToByteArray(
	@NonNull final int[] array, final int offset, final int num) {
	
	final ByteBuffer buf = ByteBuffer.allocate(num * Integer.SIZE / 8);
	buf.order(ByteOrder.nativeOrder());
	final int n8 = num % 8 + offset;
	final int n = offset + num;
	for (int i = offset; i < n8; i++) buf.putInt(array[i]);
	for (int i = n8; i < n; i += 8) {
		buf.putInt(array[i]);
		buf.putInt(array[i + 1]);
		buf.putInt(array[i + 2]);
		buf.putInt(array[i + 3]);
		buf.putInt(array[i + 4]);
		buf.putInt(array[i + 5]);
		buf.putInt(array[i + 6]);
		buf.putInt(array[i + 7]);
	}
	buf.flip();
	return buf.array();
}
 
Example 6
Source File: PrefixIdQuery.java    From geowave with Apache License 2.0 6 votes vote down vote up
@Override
public byte[] toBinary() {
  byte[] sortKeyPrefixBinary, partitionKeyBinary;
  if (partitionKey != null) {
    partitionKeyBinary = partitionKey;
  } else {
    partitionKeyBinary = new byte[0];
  }
  if (sortKeyPrefix != null) {
    sortKeyPrefixBinary = sortKeyPrefix;
  } else {
    sortKeyPrefixBinary = new byte[0];
  }
  final ByteBuffer buf =
      ByteBuffer.allocate(
          VarintUtils.unsignedIntByteLength(partitionKeyBinary.length)
              + sortKeyPrefixBinary.length
              + partitionKeyBinary.length);
  VarintUtils.writeUnsignedInt(partitionKeyBinary.length, buf);
  buf.put(partitionKeyBinary);
  buf.put(sortKeyPrefixBinary);
  return buf.array();
}
 
Example 7
Source File: UtilSerializers.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Override
public <O extends OutputShim> void write(final KryoShim<?, O> kryo, final O output, final ByteBuffer bb) {
    final byte[] b = bb.array();
    final int arrayOffset = bb.arrayOffset();
    Arrays.copyOfRange(b, arrayOffset + bb.position(), arrayOffset + bb.limit());
    output.writeInt(b.length);
    output.writeBytes(b, 0, b.length);
}
 
Example 8
Source File: BytePacket.java    From voip_android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
static public int htoll(int v) {
    ByteBuffer b = ByteBuffer.allocate(4);
    b.order(ByteOrder.nativeOrder());
    b.putInt(v);
    byte[] t = b.array();
    ByteBuffer b2 = ByteBuffer.wrap(t, 0, 4);
    b2.order(ByteOrder.LITTLE_ENDIAN);
    return b2.getInt();
}
 
Example 9
Source File: US_ASCII.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
private CoderResult encodeArrayLoop(CharBuffer src,
                                    ByteBuffer dst)
{
    char[] sa = src.array();
    int sp = src.arrayOffset() + src.position();
    int sl = src.arrayOffset() + src.limit();
    assert (sp <= sl);
    sp = (sp <= sl ? sp : sl);
    byte[] da = dst.array();
    int dp = dst.arrayOffset() + dst.position();
    int dl = dst.arrayOffset() + dst.limit();
    assert (dp <= dl);
    dp = (dp <= dl ? dp : dl);

    try {
        while (sp < sl) {
            char c = sa[sp];
            if (c < 0x80) {
                if (dp >= dl)
                    return CoderResult.OVERFLOW;
                da[dp] = (byte)c;
                sp++; dp++;
                continue;
            }
            if (sgp.parse(c, sa, sp, sl) < 0)
                return sgp.error();
            return sgp.unmappableResult();
        }
        return CoderResult.UNDERFLOW;
    } finally {
        src.position(sp - src.arrayOffset());
        dst.position(dp - dst.arrayOffset());
    }
}
 
Example 10
Source File: X11GB2312_OLD.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
protected CoderResult encodeLoop(CharBuffer src, ByteBuffer dst) {
    char[] sa = src.array();
    int sp = src.arrayOffset() + src.position();
    int sl = src.arrayOffset() + src.limit();

    byte[] da = dst.array();
    int dp = dst.arrayOffset() + dst.position();
    int dl = dst.arrayOffset() + dst.limit();

    try {
        while (sp < sl) {
            char c = sa[sp];
            if (c <= '\u007f')
                return CoderResult.unmappableForLength(1);
            int ncode = encodeDouble(c);
            if (ncode != 0 && c != '\u0000' ) {
                da[dp++] = (byte) ((ncode  >> 8) & 0x7f);
                da[dp++] = (byte) (ncode & 0x7f);
                sp++;
                continue;
            }
            return CoderResult.unmappableForLength(1);
        }
        return CoderResult.UNDERFLOW;
    } finally {
        src.position(sp - src.arrayOffset());
        dst.position(dp - dst.arrayOffset());
    }
}
 
Example 11
Source File: ListFVM.java    From aion with MIT License 5 votes vote down vote up
@Override
public byte[] serialize() {
    ByteBuffer bb = ByteBuffer.allocate(params.size() * params.get(0).serialize().length + 16);
    int elementLength = params.size();
    bb.put(PrecompiledUtilities.pad(BigInteger.valueOf(elementLength).toByteArray(), 16));

    for (BaseTypeFVM p : params) {
        bb.put(p.serialize());
    }
    return bb.array();
}
 
Example 12
Source File: V3SchemeSigner.java    From Xpatch with Apache License 2.0 5 votes vote down vote up
private static byte[] encodeSigner(V3SignatureSchemeBlock.Signer signer) {
    byte[] signedData = encodeAsLengthPrefixedElement(signer.signedData);
    byte[] signatures =
            encodeAsLengthPrefixedElement(
                    encodeAsSequenceOfLengthPrefixedPairsOfIntAndLengthPrefixedBytes(
                            signer.signatures));
    byte[] publicKey = encodeAsLengthPrefixedElement(signer.publicKey);

    // FORMAT:
    // * length-prefixed signed data
    // * uint32: minSdkVersion
    // * uint32: maxSdkVersion
    // * length-prefixed sequence of length-prefixed signatures:
    //   * uint32: signature algorithm ID
    //   * length-prefixed bytes: signature of signed data
    // * length-prefixed bytes: public key (X.509 SubjectPublicKeyInfo, ASN.1 DER encoded)
    int payloadSize =
            signedData.length
            + 4
            + 4
            + signatures.length
            + publicKey.length;

    ByteBuffer result = ByteBuffer.allocate(payloadSize);
    result.order(ByteOrder.LITTLE_ENDIAN);
    result.put(signedData);
    result.putInt(signer.minSdkVersion);
    result.putInt(signer.maxSdkVersion);
    result.put(signatures);
    result.put(publicKey);

    return result.array();
}
 
Example 13
Source File: GeometryUtils.java    From BIMserver with GNU Affero General Public License v3.0 5 votes vote down vote up
public static byte[] doubleArrayToByteArray(double[] vertices) {
	if (vertices == null) {
		return null;
	}
	ByteBuffer buffer = ByteBuffer.wrap(new byte[vertices.length * 4]);
	buffer.order(ByteOrder.LITTLE_ENDIAN);
	DoubleBuffer asDoubleBuffer = buffer.asDoubleBuffer();
	for (double d : vertices) {
		asDoubleBuffer.put(d);
	}
	return buffer.array();
}
 
Example 14
Source File: ByteUtil.java    From Jose4j with Apache License 2.0 4 votes vote down vote up
public static byte[] getBytes(int intValue)
{
    ByteBuffer byteBuffer = ByteBuffer.allocate(4);
    byteBuffer.putInt(intValue);
    return byteBuffer.array();
}
 
Example 15
Source File: TextMessageReader.java    From singer with Apache License 2.0 4 votes vote down vote up
public static String bufToString(ByteBuffer buffer) {
  String string = new String(buffer.array(), 0, buffer.limit(), Charsets.UTF_8);
  return string;
}
 
Example 16
Source File: SJIS_0213.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
protected CoderResult encodeArrayLoop(CharBuffer src, ByteBuffer dst) {
    char[] sa = src.array();
    int sp = src.arrayOffset() + src.position();
    int sl = src.arrayOffset() + src.limit();
    byte[] da = dst.array();
    int dp = dst.arrayOffset() + dst.position();
    int dl = dst.arrayOffset() + dst.limit();

    try {
        while (sp < sl) {
            int db;
            char c = sa[sp];
            if (leftoverBase != 0) {
                boolean isComp = false;
                db = encodeComposite(leftoverBase, c);
                if (db == UNMAPPABLE)
                    db = encodeChar(leftoverBase);
                else
                    isComp = true;
                if (dl - dp < 2)
                    return CoderResult.OVERFLOW;
                da[dp++] = (byte)(db >> 8);
                da[dp++] = (byte)db;
                leftoverBase = 0;
                if (isComp) {
                    sp++;
                    continue;
                }
            }
            if (isCompositeBase(c)) {
                leftoverBase = c;
            } else {
                db = encodeChar(c);
                if (db <= MAX_SINGLEBYTE) {      // SingleByte
                    if (dl <= dp)
                        return CoderResult.OVERFLOW;
                    da[dp++] = (byte)db;
                } else if (db != UNMAPPABLE) {   // DoubleByte
                    if (dl - dp < 2)
                        return CoderResult.OVERFLOW;
                    da[dp++] = (byte)(db >> 8);
                    da[dp++] = (byte)db;
                } else if (Character.isHighSurrogate(c)) {
                    if ((sp + 1) == sl)
                        return CoderResult.UNDERFLOW;
                    char c2 = sa[sp + 1];
                    if (!Character.isLowSurrogate(c2))
                        return CoderResult.malformedForLength(1);
                    db = encodeSurrogate(c, c2);
                    if (db == UNMAPPABLE)
                        return CoderResult.unmappableForLength(2);
                    if (dl - dp < 2)
                        return CoderResult.OVERFLOW;
                    da[dp++] = (byte)(db >> 8);
                    da[dp++] = (byte)db;
                    sp++;
                } else if (Character.isLowSurrogate(c)) {
                    return CoderResult.malformedForLength(1);
                } else {
                    return CoderResult.unmappableForLength(1);
                }
            }
            sp++;
        }
        return CoderResult.UNDERFLOW;
    } finally {
        src.position(sp - src.arrayOffset());
        dst.position(dp - dst.arrayOffset());
    }
}
 
Example 17
Source File: DBCS_IBM_ASCII_Encoder.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
private CoderResult encodeArrayLoop(CharBuffer src, ByteBuffer dst) {
    char[] sa = src.array();
    int sp = src.arrayOffset() + src.position();
    int sl = src.arrayOffset() + src.limit();
    byte[] da = dst.array();
    int dp = dst.arrayOffset() + dst.position();
    int dl = dst.arrayOffset() + dst.limit();
    int outputSize = 0;             // size of output

    try {
        while (sp < sl) {
            int index;
            int theBytes;
            char c = sa[sp];
            if (Surrogate.is(c)) {
                if (sgp.parse(c, sa, sp, sl) < 0)
                    return sgp.error();
                return sgp.unmappableResult();
            }
            if (c >= '\uFFFE')
                return CoderResult.unmappableForLength(1);

            index = index1[((c & mask1) >> shift)]
                            + (c & mask2);
            if (index < 15000)
                theBytes = (int)(index2.charAt(index));
            else
                theBytes = (int)(index2a.charAt(index-15000));
            b1 = (byte)((theBytes & 0x0000ff00)>>8);
            b2 = (byte)(theBytes & 0x000000ff);

            if (b1 == 0x00 && b2 == 0x00
                && c != '\u0000') {
                    return CoderResult.unmappableForLength(1);
            }

            if (b1 == 0) {
                if (dl - dp < 1)
                    return CoderResult.OVERFLOW;
                da[dp++] = (byte) b2;
            } else {
                if (dl - dp < 2)
                    return CoderResult.OVERFLOW;
                da[dp++] = (byte) b1;
                da[dp++] = (byte) b2;
            }
            sp++;
        }
        return CoderResult.UNDERFLOW;
    } finally {
        src.position(sp - src.arrayOffset());
        dst.position(dp - dst.arrayOffset());
    }
}
 
Example 18
Source File: SCSIWrite10.java    From Pincho-Usb-Mass-Storage-for-Android with MIT License 4 votes vote down vote up
@Override
public byte[] getSCSICommandBuffer()
{
    ByteBuffer buffer = ByteBuffer.allocate(10);
    buffer.put(WRITE10_OPERATION_CODE);
    byte firstByte = 0x00;
    switch(wrProtect)
    {
        case 0:
            firstByte &= ~(1 << 7);
            firstByte &= ~(1 << 6);
            firstByte &= ~(1 << 5);
            break;
        case 1:
            firstByte &= ~(1 << 7);
            firstByte &= ~(1 << 6);
            firstByte |= (1 << 5);
            break;
        case 2:
            firstByte &= ~(1 << 7);
            firstByte |= (1 << 6);
            firstByte &= ~(1 << 5);
        case 3:
            firstByte &= ~(1 << 7);
            firstByte |= (1 << 6);
            firstByte |= (1 << 5);
            break;
        case 4:
            firstByte |= (1 << 7);
            firstByte &= ~(1 << 6);
            firstByte &= ~(1 << 5);
            break;
        case 5:
            firstByte |= (1 << 7);
            firstByte &= ~(1 << 6);
            firstByte |= (1 << 5);
            break;
        case 6:
            firstByte |= (1 << 7);
            firstByte |= (1 << 6);
            firstByte &= ~(1 << 5);
            break;
        case 7:
            firstByte |= (1 << 7);
            firstByte |= (1 << 6);
            firstByte |= (1 << 5);
            break;
    }

    if(dpo)
        firstByte |= (1 << 4);
    if(fua)
        firstByte |= (1 << 3);
    if(fuaNv)
        firstByte |= (1 << 1);

    buffer.put(firstByte);
    buffer.putInt(logicalBlockAddress);

    buffer.put(convertToByte(groupNumber, 1));
    buffer.put(convertToByte(transferLength, 2));
    buffer.put(control);
    return buffer.array();
}
 
Example 19
Source File: SirfUtils.java    From UsbGps4Droid with GNU General Public License v3.0 4 votes vote down vote up
public static byte[] genSirfCommand(String commandHexa) {
    int length = commandHexa.length() / 2;
    ByteBuffer command = ByteBuffer.allocate(length);
    command.put(new BigInteger(commandHexa, 16).toByteArray(), 1, length);
    return command.array();
}
 
Example 20
Source File: RLPEncoder.java    From headlong with Apache License 2.0 2 votes vote down vote up
/**
 * Returns the RLP encoding of the given byte string.
 *
 * @param byteString the byte string to be encoded
 * @return the encoding
 */
public static byte[] encodeString(byte[] byteString) {
    ByteBuffer bb = ByteBuffer.allocate(stringEncodedLen(byteString));
    encodeString(byteString, bb);
    return bb.array();
}