Here you can find the source of toBytes(String str, byte[] bytes, int index)
Parameter | Description |
---|---|
str | a parameter |
bytes | a parameter |
index | a parameter |
public static int toBytes(String str, byte[] bytes, int index)
//package com.java2s; //License from project: Apache License public class Main { /**/*from ww w . j a v a 2 s.co m*/ * Convert int to bytes and store them in the array starting at the given index. * * @param val * @param bytes * @param index * @return the ending index, exclusive. */ public static int toBytes(int val, byte[] bytes, int index) { int typeBytes = Integer.SIZE / Byte.SIZE; checkBounds(bytes, index, typeBytes); for (int i = 0; i < typeBytes; i++) { int shiftBits = Byte.SIZE * (typeBytes - i - 1); byte b = (byte) (val >> shiftBits); bytes[index++] = b; } return index; } /** * Convert long to bytes and store them in the array starting at the given index. * @param val * @param bytes * @param index * @return the ending index, exclusive. */ public static int toBytes(long val, byte[] bytes, int index) { int typeBytes = Long.SIZE / Byte.SIZE; checkBounds(bytes, index, typeBytes); for (int i = 0; i < typeBytes; i++) { int shiftBits = Byte.SIZE * (typeBytes - i - 1); byte b = (byte) (val >> shiftBits); bytes[index++] = b; } return index; } /** * Convert string to bytes and store them in the array starting at the given index. * * @param str * @param bytes * @param index * @return the ending index, exclusive. */ public static int toBytes(String str, byte[] bytes, int index) { int typeBytes = Character.SIZE / Byte.SIZE; checkBounds(bytes, index, typeBytes * str.length()); for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); for (int j = typeBytes - 1; j >= 0; j--) { int shiftBits = Byte.SIZE * j; byte b = (byte) (c >> shiftBits); bytes[index++] = b; } } return index; } /** * Utility method used to bounds check the byte array * and requested offset & length values. * * @param bytes * @param offset * @param length */ public static void checkBounds(byte[] bytes, int offset, int length) { if (length < 0) throw new IndexOutOfBoundsException("Index out of range: " + length); if (offset < 0) throw new IndexOutOfBoundsException("Index out of range: " + offset); if (offset > bytes.length - length) throw new IndexOutOfBoundsException("Index out of range: " + (offset + length)); } }