public class Bytes extends Object implements Comparable<Bytes>, Serializable, Iterable<Byte>
It supports byte ordering (little/big endianness).
This class is immutable as long as the internal array is not changed from outside (which can't be assured, when
using using wrap()). It is possible to create a mutable version (see MutableBytes).
Example:
Bytes b = Bytes.from(array).mutable();
b.not();
System.out.println(b.encodeHex());
BytesTransformers.sortUnsigned().| Modifier and Type | Method and Description |
|---|---|
static Bytes |
allocate(int length)
Creates a new instance with an empty array filled with zeros.
|
static Bytes |
allocate(int length,
byte defaultValue)
Creates a new instance with an empty array filled with given defaultValue
|
Bytes |
and(byte[] secondArray)
Bitwise AND operation on the whole internal byte array.
|
Bytes |
and(Bytes bytes)
Bitwise AND operation on the whole internal byte array.
|
Bytes |
append(byte singleByte)
Creates a new instance with the current array appended to the provided data (ie.
|
Bytes |
append(byte[]... arrays)
Creates a new instance with the current array appended to the provided data (ie.
|
Bytes |
append(byte[] secondArray)
Creates a new instance with the current array appended to the provided data (ie.
|
Bytes |
append(Bytes bytes)
Creates a new instance with the current array appended to the provided data (ie.
|
Bytes |
append(char char2Bytes)
Creates a new instance with the current array appended to the provided data (ie.
|
Bytes |
append(CharSequence stringUtf8)
Creates a new instance with the current array appended to the provided utf-8 encoded representation of this string
|
Bytes |
append(CharSequence string,
Charset charset)
Creates a new instance with the current array appended to the provided string with provided encoding
|
Bytes |
append(int integer4Bytes)
Creates a new instance with the current array appended to the provided data (ie.
|
Bytes |
append(long long8Bytes)
Creates a new instance with the current array appended to the provided data (ie.
|
Bytes |
append(short short2Bytes)
Creates a new instance with the current array appended to the provided data (ie.
|
Bytes |
appendNullSafe(byte[] secondArrayNullable)
Creates a new instance with the current array appended to the provided data (ie.
|
byte[] |
array()
The reference of te internal byte-array.
|
boolean |
bitAt(int bitIndex)
Returns the
bit value as boolean at the specified index. |
ByteBuffer |
buffer()
The internal byte array wrapped in a
ByteBuffer instance. |
byte |
byteAt(int index)
Returns the
byte value at the specified index. |
ByteOrder |
byteOrder()
Get the set byte order/endianness.
|
Bytes |
byteOrder(ByteOrder byteOrder)
Set the byte order or endianness of this instance.
|
char |
charAt(int index)
Returns the
char value at the specified index. |
int |
compareTo(Bytes o)
Compares this bytes instance to another.
|
boolean |
contains(byte target)
Checks if given byte value is contained in internal array
|
Bytes |
copy()
Creates a new instance with a copy of the internal byte array and all other attributes.
|
Bytes |
copy(int offset,
int length)
Creates a new instance with a copy of the internal byte array and all other attributes.
|
int |
count(byte target)
Traverses the internal byte array counts the occurrences of given byte.
|
int |
count(byte[] pattern)
Traverses the internal byte array counts the occurrences of given pattern array.
|
Bytes |
duplicate()
Create a new instance which shares the same underlying array
|
static Bytes |
empty()
Creates an Byte instance with an internal empty byte array.
|
String |
encode(BinaryToTextEncoding.Encoder encoder)
Encode the internal byte-array with given encoder.
|
String |
encodeBase32()
Base32 RFC4648 string representation of the internal byte array (not Base32 hex alphabet extension)
|
String |
encodeBase36()
Deprecated.
use
encodeRadix(int) instead; will be removed in v1.0+ |
String |
encodeBase64()
Base64 representation with padding.
|
String |
encodeBase64(boolean urlSafe,
boolean withPadding)
Base64 representation with either padding or without and with or without URL and filename safe alphabet.
|
String |
encodeBase64Url()
Base64 representation with padding.
|
String |
encodeBinary()
Binary (aka "1" and "0") representation.
|
String |
encodeCharset(Charset charset)
String representation with given charset encoding
|
byte[] |
encodeCharsetToBytes(Charset charset)
Byte array representation with given charset encoding.
|
String |
encodeDec()
Decimal (0-9) representation.
|
String |
encodeHex()
Base16 or Hex representation in lowercase.
|
String |
encodeHex(boolean upperCase)
Base16 or Hex representation.
|
String |
encodeOctal()
Octal (0-7) representation.
|
String |
encodeRadix(int radix)
Encodes the internal array in given radix representation (e.g.
|
String |
encodeUtf8()
UTF-8 representation of this byte array
|
byte[] |
encodeUtf8ToBytes()
UTF-8 representation of this byte array as byte array
|
boolean |
endsWith(byte[] subArray)
Checks if the given sub array is equal to the end of given array.
|
double |
entropy()
Calculates the entropy of the internal byte array.
|
boolean |
equals(byte[] anotherArray)
Compares the inner array with given array
|
boolean |
equals(Byte[] anotherArray)
Compares the inner array with given array.
|
boolean |
equals(ByteBuffer buffer)
Compares the inner array with the inner array of given ByteBuffer.
|
boolean |
equals(Object o)
Checks if this instance is equal to given other instance o
|
boolean |
equalsConstantTime(byte[] anotherArray)
Compares the inner array with given array.
|
boolean |
equalsContent(Bytes other)
Checks only for internal array content
|
static Bytes |
from(BigInteger bigInteger)
Creates a new instance from given
BigInteger. |
static Bytes |
from(BitSet set)
Creates a new instance from given
BitSet. |
static Bytes |
from(boolean booleanValue)
Creates a new instance from given boolean.
|
static Bytes |
from(byte singleByte)
Creates a new single array element array instance from given byte
|
static Bytes |
from(byte[]... moreArrays)
Creates a new instance from given array of byte arrays
|
static Bytes |
from(byte[] byteArrayToCopy)
Creates a new instance from given collections of single bytes.
|
static Bytes |
from(Byte[] boxedObjectArray)
Creates a new instance from given object byte array.
|
static Bytes |
from(byte[] array,
int offset,
int length)
Creates a new instance from a slice of given array
|
static Bytes |
from(ByteBuffer buffer)
Creates a new instance from given
ByteBuffer. |
static Bytes |
from(byte firstByte,
byte... moreBytes)
Creates a new instance from given collections of single bytes.
|
static Bytes |
from(Bytes... moreBytes)
Creates a new instance from given array of byte arrays
|
static Bytes |
from(char char2Byte)
Creates a new instance from given unsigned 2 byte char.
|
static Bytes |
from(char[] charArray)
Creates a new instance from given char array using utf-8 encoding
|
static Bytes |
from(char[] charArray,
Charset charset)
Creates a new instance from given char array.
|
static Bytes |
from(char[] charArray,
Charset charset,
int offset,
int length)
Creates a new instance from given char array with given range.
|
static Bytes |
from(CharBuffer buffer)
Creates a new instance from given
CharBuffer. |
static Bytes |
from(CharSequence utf8String)
Creates a new instance from given utf-8 encoded string
|
static Bytes |
from(CharSequence string,
Charset charset)
Creates a new instance from given string
|
static Bytes |
from(CharSequence utf8String,
Normalizer.Form form)
Creates a new instance from normalized form of given utf-8 encoded string
|
static Bytes |
from(Collection<Byte> bytesCollection)
Creates a new instance from given collections.
|
static Bytes |
from(DataInput dataInput,
int length)
Reads given
DataInput and creates a new instance from read data |
static Bytes |
from(double double8Byte)
Creates a new instance from given 8 byte floating point number (double).
|
static Bytes |
from(File file)
Reads given file and returns the byte content.
|
static Bytes |
from(File file,
int offset,
int length)
Reads given file and returns the byte content.
|
static Bytes |
from(float float4byte)
Creates a new instance from given 4 byte floating point number (float).
|
static Bytes |
from(InputStream stream)
Reads given whole input stream and creates a new instance from read data
|
static Bytes |
from(InputStream stream,
int maxLength)
Reads given input stream up to maxLength and creates a new instance from read data.
|
static Bytes |
from(int... intArray)
Creates a new instance from given 4 byte integer array.
|
static Bytes |
from(int integer4byte)
Creates a new instance from given 4 byte integer.
|
static Bytes |
from(IntBuffer buffer)
Creates a new instance from given
IntBuffer. |
static Bytes |
from(long... longArray)
Creates a new instance from given 8 byte long array.
|
static Bytes |
from(long long8byte)
Creates a new instance from given 8 byte long.
|
static Bytes |
from(short short2Byte)
Creates a new instance from given 2 byte short.
|
static Bytes |
from(UUID uuid)
Convert UUID to a newly generated 16 byte long array representation.
|
static Bytes |
fromNullSafe(byte[] byteArrayToCopy)
Creates a new instance from given collections of single bytes.
|
Bytes |
hash(String algorithm)
Calculates hash with provided algorithm on the underlying byte array and returns a byte instance
containing the hash.
|
int |
hashCode() |
Bytes |
hashMd5()
Calculates md5 on the underlying byte array and returns a byte instance containing the hash.
|
Bytes |
hashSha1()
Calculates sha1 on the underlying byte array and returns a byte instance containing the hash.
|
Bytes |
hashSha256()
Calculates sha256 on the underlying byte array and returns a byte instance containing the hash.
|
int |
indexOf(byte target)
Returns the index of the first appearance of the value
target in
array. |
int |
indexOf(byte[] subArray)
Returns the start position of the first occurrence of the specified
target within array, or -1 if there is no such occurrence. |
int |
indexOf(byte[] subArray,
int fromIndex)
Returns the start position of the first occurrence of the specified
target within array from given start index 'fromIndex', or -1
if there is no such occurrence. |
int |
indexOf(byte target,
int fromIndex)
Returns the index of the first appearance of the value
target in
array from given start index 'fromIndex'. |
InputStream |
inputStream()
Creates an input stream with the same backing data as the intern array of this instance
|
int |
intAt(int index)
Returns the
int value at the specified index. |
boolean |
isEmpty()
Checks the internal array for emptiness.
|
boolean |
isMutable()
Checks if instance is mutable
|
boolean |
isReadOnly()
Check if this instance is read only
|
Iterator<Byte> |
iterator() |
int |
lastIndexOf(byte target)
Returns the index of the last appearance of the value
target in
array. |
Bytes |
leftShift(int shiftCount)
Bitwise left shifting of internal byte array (i.e.
|
int |
length()
The byte length of the underlying byte array.
|
int |
lengthBit()
The bit length of the underlying byte array.
|
long |
longAt(int index)
Returns the
long value at the specified index. |
MutableBytes |
mutable()
Returns a mutable version of this instance with sharing the same underlying byte-array.
|
Bytes |
not()
Bitwise not operation on the whole internal byte array.
|
Bytes |
or(byte[] secondArray)
Bitwise OR operation on the whole internal byte array.
|
Bytes |
or(Bytes bytes)
Bitwise OR operation on the whole internal byte array.
|
static Bytes |
parse(CharSequence encoded,
BinaryToTextEncoding.Decoder decoder)
Parsing of arbitrary encoded format
|
static Bytes |
parseBase32(CharSequence base32Rfc4648String)
Parsing of base32/RFC 4648 encoded byte arrays.
|
static Bytes |
parseBase36(CharSequence base36String)
Deprecated.
use
parseRadix(CharSequence, int) with 36 instead; will be removed in v1.0+ |
static Bytes |
parseBase64(CharSequence base64String)
Parsing of base64 encoded byte arrays.
|
static Bytes |
parseBinary(CharSequence binaryString)
Parses a big endian binary string (e.g.
|
static Bytes |
parseDec(CharSequence decString)
Parsing of decimal encoded byte arrays.
|
static Bytes |
parseHex(CharSequence hexString)
Parsing of base16/HEX encoded byte arrays.
|
static Bytes |
parseOctal(CharSequence octalString)
Parsing of octal encoded byte arrays.
|
static Bytes |
parseRadix(CharSequence radixNumberString,
int radix)
Encodes with given radix string representation (e.g.
|
static Bytes |
random(int length)
A new instance with random bytes.
|
static Bytes |
random(int length,
Random random)
A new instance with random bytes.
|
ReadOnlyBytes |
readOnly()
Returns a new read-only byte instance.
|
Bytes |
resize(int newByteLength)
Copies the specified array, truncating or padding with zeros (if necessary)
so the copy has the specified length.
|
Bytes |
resize(int newByteLength,
BytesTransformer.ResizeTransformer.Mode mode)
Copies the specified array, truncating or padding with zeros (if necessary)
so the copy has the specified length.
|
Bytes |
reverse()
Reverses the internal bytes in the array (not bits in each byte)
|
Bytes |
rightShift(int shiftCount)
Bitwise unsigned/logical right shifting of internal byte array (i.e.
|
short |
shortAt(int index)
Returns the
short value at the specified index. |
boolean |
startsWith(byte[] subArray)
Checks if the given sub array is equal to the start of given array.
|
Bytes |
switchBit(int bitPosition)
Returns a Byte whose value is equivalent to this Byte with the designated bit switched.
|
Bytes |
switchBit(int bitPosition,
boolean newBitValue)
Returns a Byte whose value is equivalent to this Byte with the designated bit set to newBitValue.
|
BigInteger |
toBigInteger()
The internal byte array wrapped in a
BigInteger instance. |
BitSet |
toBitSet()
Returns a copy of the internal byte-array as
BitSet type |
Byte[] |
toBoxedArray()
Returns a copy of the internal byte-array as boxed primitive array.
|
byte |
toByte()
If the underlying byte array is exactly 1 byte / 8 bit long, returns signed two-complement
representation for a Java byte value.
|
char |
toChar()
If the underlying byte array is exactly 2 byte / 16 bit long, return unsigned two-complement
representation for a Java char integer value.
|
char[] |
toCharArray()
Decodes the internal byte array to UTF-8 char array.
|
char[] |
toCharArray(Charset charset)
Decodes the internal byte array with given charset to a char array.
|
double |
toDouble()
If the underlying byte array is exactly 8 byte / 64 bit long, return the
representation for a Java double value.
|
double[] |
toDoubleArray()
Converts the internal byte array to an double array, that is, every 8 bytes will be packed into a single double.
|
float |
toFloat()
If the underlying byte array is exactly 4 byte / 32 bit long, return the
representation for a Java float value.
|
float[] |
toFloatArray()
Converts the internal byte array to an float array, that is, every 4 bytes will be packed into a single float.
|
int |
toInt()
If the underlying byte array is exactly 4 byte / 32 bit long, return signed two-complement
representation for a Java signed integer value.
|
int[] |
toIntArray()
Converts the internal byte array to an int array, that is, every 4 bytes will be packed into a single int.
|
List<Byte> |
toList()
Returns a copy of the internal byte-array as
List collection type
This requires a time and space complexity of O(n). |
long |
toLong()
If the underlying byte array is exactly 8 byte / 64 bit long, return signed two-complement
representation for a Java signed long integer value.
|
long[] |
toLongArray()
Converts the internal byte array to an long array, that is, every 8 bytes will be packed into a single long.
|
short |
toShort()
If the underlying byte array is exactly 2 byte / 16 bit long, return signed two-complement
representation for a Java short integer value.
|
String |
toString()
A constant length output toString() implementation, which only shows the byte length and at most 8 bytes preview in hex
representation.
|
int |
toUnsignedByte()
If the underlying byte array is exactly 1 byte / 8 bit long, returns unsigned two-complement
representation for a Java byte value wrapped in an 4 byte int.
|
UUID |
toUUID()
Creates a
UUID instance of the internal byte array. |
Bytes |
transform(BytesTransformer transformer)
Generic transformation of this instance.
|
static Bytes |
unsecureRandom(int length)
A new instance with pseudo random bytes using an unsecure random number generator.
|
static Bytes |
unsecureRandom(int length,
long seed)
A new instance with pseudo random bytes using an unsecure random number generator.
|
int |
unsignedByteAt(int index)
Returns the unsigned
byte value at the specified index as an int. |
boolean |
validate(BytesValidator... bytesValidators)
Applies all given validators and returns true if all of them return true (default AND concatenation).
|
boolean |
validateNotOnlyZeros()
Checks the content of each byte for 0 values
|
static Bytes |
wrap(byte[] array)
Creates a new instance with given byte array.
|
static Bytes |
wrap(byte[] array,
ByteOrder byteOrder)
Creates a new instance with given byte array.
|
static Bytes |
wrap(Bytes bytes)
Creates a new reference backed by the same byte array.
|
static Bytes |
wrapNullSafe(byte[] array)
Creates a new instance with given byte array.
|
Bytes |
xor(byte[] secondArray)
Bitwise XOR operation on the whole internal byte array.
|
Bytes |
xor(Bytes bytes)
Bitwise XOR operation on the whole internal byte array.
|
clone, finalize, getClass, notify, notifyAll, wait, wait, waitforEach, spliteratorpublic static Bytes allocate(int length)
length - of the internal arraypublic static Bytes allocate(int length, byte defaultValue)
length - of the internal arraydefaultValue - to fill withpublic static Bytes empty()
allocate(int) with 0.public static Bytes wrap(Bytes bytes)
bytes - to use as templatepublic static Bytes wrapNullSafe(byte[] array)
The new instance will be backed by the given byte array; that is, modifications to the bytes will cause the array to be modified and vice versa.
If given array is null, a zero length byte array will be created and used instead.
array - to use directly or zero length byte arraypublic static Bytes wrap(byte[] array)
The new instance will be backed by the given byte array; that is, modifications to the bytes will cause the array to be modified and vice versa.
array - to use directlypublic static Bytes wrap(byte[] array, ByteOrder byteOrder)
The new instance will be backed by the given byte array; that is, modifications to the bytes will cause the array to be modified and vice versa.
array - to use directlybyteOrder - the byte order of passed arraypublic static Bytes from(byte[] byteArrayToCopy)
byteArrayToCopy - must not be null and will not be used directly, but a copypublic static Bytes fromNullSafe(byte[] byteArrayToCopy)
If given array is null, a zero length byte array will be created and used instead.
byteArrayToCopy - will not be used directly, but a copy; may be nullpublic static Bytes from(byte[] array, int offset, int length)
array - to sliceoffset - start positionlength - lengthpublic static Bytes from(byte[]... moreArrays)
moreArrays - must not be nullpublic static Bytes from(Bytes... moreBytes)
moreBytes - must not be nullpublic static Bytes from(Collection<Byte> bytesCollection)
bytesCollection - to create frompublic static Bytes from(Byte[] boxedObjectArray)
boxedObjectArray - to create frompublic static Bytes from(byte singleByte)
singleByte - to create frompublic static Bytes from(byte firstByte, byte... moreBytes)
firstByte - must not be null and will not be used directly, but a copymoreBytes - more bytes varargpublic static Bytes from(boolean booleanValue)
new byte[] {1} if booleanValue is true and new byte[] {0} if
booleanValue is false.booleanValue - to convert (false is zero, true is one)public static Bytes from(char char2Byte)
char2Byte - to create frompublic static Bytes from(short short2Byte)
short2Byte - to create frompublic static Bytes from(int integer4byte)
integer4byte - to create frompublic static Bytes from(int... intArray)
intArray - to create frompublic static Bytes from(long long8byte)
long8byte - to create frompublic static Bytes from(long... longArray)
longArray - to create frompublic static Bytes from(float float4byte)
float4byte - to create frompublic static Bytes from(double double8Byte)
double8Byte - to create frompublic static Bytes from(ByteBuffer buffer)
ByteBuffer.
Will use the same backing byte array and honour the buffer's byte order.buffer - to get the byte array from (must not be null)public static Bytes from(CharBuffer buffer)
CharBuffer.
Will ignore buffer's byte order and use ByteOrder.BIG_ENDIANbuffer - to get the char array from (must not be null)public static Bytes from(IntBuffer buffer)
IntBuffer.
Will ignore buffer's byte order and use ByteOrder.BIG_ENDIANbuffer - to get the int array from (must not be null)public static Bytes from(BitSet set)
BitSet.set - to get the byte array frompublic static Bytes from(BigInteger bigInteger)
BigInteger.bigInteger - to get the byte array frompublic static Bytes from(InputStream stream)
stream - to read frompublic static Bytes from(InputStream stream, int maxLength)
stream - to read frommaxLength - read to this maxLength or end of streampublic static Bytes from(DataInput dataInput, int length)
DataInput and creates a new instance from read datadataInput - to read fromlength - how many bytes should be readpublic static Bytes from(File file)
file - to read fromIllegalArgumentException - if file does not existIllegalStateException - if file could not be readpublic static Bytes from(File file, int offset, int length)
RandomAccessFile under the hood.file - to read fromoffset - byte offset from zero position of the filelength - to read from offsetIllegalArgumentException - if file does not existIllegalStateException - if file could not be readpublic static Bytes from(CharSequence utf8String)
utf8String - to get the internal byte array frompublic static Bytes from(CharSequence utf8String, Normalizer.Form form)
utf8String - to get the internal byte array fromform - to normalize, usually you want Normalizer.Form.NFKD for compatibilitypublic static Bytes from(CharSequence string, Charset charset)
string - to get the internal byte array fromcharset - used to decode the stringpublic static Bytes from(char[] charArray)
charArray - to get the internal byte array frompublic static Bytes from(char[] charArray, Charset charset)
charArray - to get the internal byte array fromcharset - charset to be used to decode the char arraypublic static Bytes from(char[] charArray, Charset charset, int offset, int length)
charArray - to get the internal byte array fromcharset - charset to be used to decode the char arrayoffset - start position (from given char array not encoded byte array out)length - length in relation to offset (from given char array not encoded byte array out)public static Bytes from(UUID uuid)
uuid - to convert to arraypublic static Bytes parseBinary(CharSequence binaryString)
10010001)binaryString - the encoded stringpublic static Bytes parseOctal(CharSequence octalString)
octalString - the encoded stringpublic static Bytes parseDec(CharSequence decString)
decString - the encoded stringpublic static Bytes parseRadix(CharSequence radixNumberString, int radix)
BigInteger.toString(int).
This is usually a number encoding, not a data encoding (ie. leading zeros are not preserved), but this implementation tries to preserve the leading zeros, to keep the in/output byte length size the same, but use at your own risk!
radixNumberString - the encoded stringradix - radix of the String representation (supported are 2-36)public static Bytes parseHex(CharSequence hexString)
a-f (also mixed case)0x which will be ignoredhexString - the encoded stringIllegalArgumentException - if string contains something else than [0-9a-fA-F]public static Bytes parseBase32(CharSequence base32Rfc4648String)
Uses the RFC 4648 non-hex alphabet, see Base32 alphabet.
base32Rfc4648String - the encoded string@Deprecated public static Bytes parseBase36(CharSequence base36String)
parseRadix(CharSequence, int) with 36 instead; will be removed in v1.0+This is usually a number encoding, not a data encoding (ie. leading zeros are not preserved), but this implementation tries to preserve the leading zeros, to keep the in/output byte length size the same.
base36String - the encoded stringpublic static Bytes parseBase64(CharSequence base64String)
base64String - the encoded stringpublic static Bytes parse(CharSequence encoded, BinaryToTextEncoding.Decoder decoder)
encoded - the encoded stringdecoder - the decoder used to decode the stringpublic static Bytes random(int length)
SecureRandom instance.length - desired array lengthpublic static Bytes unsecureRandom(int length)
random(int) per default.
ONLY USE IN NON-SECURITY RELEVANT CONTEXT!
length - desired array lengthpublic static Bytes unsecureRandom(int length, long seed)
In production code use random(int) per default.
ONLY USE IN NON-SECURITY RELEVANT CONTEXT!
length - desired array lengthseed - used to seed random number generator - using same seed will generate same numberspublic static Bytes random(int length, Random random)
length - desired array lengthrandom - to create the entropy for the random bytespublic Bytes append(Bytes bytes)
This will create a new byte array internally, so it is not suitable to use as extensive builder pattern -
use ByteBuffer or ByteArrayOutputStream for that.
bytes - to appendpublic Bytes append(byte singleByte)
singleByte - to appendpublic Bytes append(char char2Bytes)
char2Bytes - to appendpublic Bytes append(short short2Bytes)
short2Bytes - to appendpublic Bytes append(int integer4Bytes)
integer4Bytes - to appendpublic Bytes append(long long8Bytes)
long8Bytes - to appendpublic Bytes append(byte[]... arrays)
append(byte[]) call
and therefore generating intermediate copies of the byte array, making this approach use less memory.arrays - to appendpublic Bytes append(byte[] secondArray)
secondArray - to appendpublic Bytes appendNullSafe(byte[] secondArrayNullable)
If given array is null, the nothing will be appended.
secondArrayNullable - to append, may be nullpublic Bytes append(CharSequence stringUtf8)
stringUtf8 - string used to get utf-8 bytes frompublic Bytes append(CharSequence string, Charset charset)
string - string used to get bytes fromcharset - encoding of provided stringpublic Bytes xor(Bytes bytes)
transform(BytesTransformer).bytes - must be of same length as this instancepublic Bytes xor(byte[] secondArray)
transform(BytesTransformer).secondArray - must be of same length as this instancepublic Bytes and(Bytes bytes)
transform(BytesTransformer).bytes - must be of same length as this instancepublic Bytes and(byte[] secondArray)
transform(BytesTransformer).secondArray - must be of same length as this instancepublic Bytes or(Bytes bytes)
transform(BytesTransformer).bytes - must be of same length as this instancepublic Bytes or(byte[] secondArray)
transform(BytesTransformer).secondArray - must be of same length as this instancepublic Bytes not()
transform(BytesTransformer).public Bytes leftShift(int shiftCount)
<<). Unlike BigInteger's implementation, this one will never
grow or shrink the underlying array. Either a bit is pushed out of the array or a zero is pushed in.
See the considerations about possible in-place operation in transform(BytesTransformer).
shiftCount - how many bits (not bytes)public Bytes rightShift(int shiftCount)
>>>). Unlike
BigInteger's implementation, this one will never grow or shrink the underlying array. Either a bit is pushed
out of the array or a zero is pushed in.
See the considerations about possible in-place operation in transform(BytesTransformer).
shiftCount - how many bits (not bytes)public Bytes switchBit(int bitPosition, boolean newBitValue)
bitPosition - not to confuse with byte positionnewBitValue - if true set to 1, 0 otherwisepublic Bytes switchBit(int bitPosition)
bitPosition - not to confuse with byte positionpublic Bytes copy()
public Bytes copy(int offset, int length)
offset - starting position in the source arraylength - of the new instancepublic Bytes reverse()
See the considerations about possible in-place operation in transform(BytesTransformer).
public Bytes resize(int newByteLength)
(byte)0.
Resize from LSB or length, so an array [0,1,2,3] resized to 3 will result in [1,2,3] or resized to 5 [0,0,1,2,3]. So when a 8 byte value resized to 4 byte will result in the same 32 bit integer value
newByteLength - the length of the copy to be returnedpublic Bytes resize(int newByteLength, BytesTransformer.ResizeTransformer.Mode mode)
(byte)0.
Modes:
BytesTransformer.ResizeTransformer.Mode.RESIZE_KEEP_FROM_ZERO_INDEX: Resize from MSB or index 0;
so an array [0,1,2,3] resized to 3 will result in [0,1,2] or resized to 5 [0,1,2,3,0]BytesTransformer.ResizeTransformer.Mode.RESIZE_KEEP_FROM_MAX_LENGTH: Resize from LSB or length;
so an array [0,1,2,3] resized to 3 will result in [1,2,3] or resized to 5 [0,0,1,2,3]newByteLength - the length of the copy to be returnedmode - from which end the length will start to count (either index 0 or length())public Bytes hashMd5()
IllegalArgumentException - if the message digest algorithm can not be found in the security providerspublic Bytes hashSha1()
IllegalArgumentException - if the message digest algorithm can not be found in the security providerspublic Bytes hashSha256()
IllegalArgumentException - if the message digest algorithm can not be found in the security providerspublic Bytes hash(String algorithm)
algorithm - same format as passed to MessageDigest.getInstance(String)IllegalArgumentException - if the message digest algorithm can not be found in the security providerspublic Bytes transform(BytesTransformer transformer)
This transformation might be done in-place (ie. without copying the internal array and overwriting its old state),
or on a copy of the internal data, depending on the type (e.g. MutableBytes) and if the operation can be done
in-place. Therefore the caller has to ensure that certain side-effects, which occur due to the changing of the internal
data, do not create bugs in his/her code. Usually immutability is preferred, but when handling many or big byte arrays,
mutability enables drastically better performance.
transformer - used to transform this instancepublic boolean validateNotOnlyZeros()
public boolean validate(BytesValidator... bytesValidators)
bytesValidators - array of validators to check against the byte arraypublic int length()
public int lengthBit()
public boolean isEmpty()
public ByteOrder byteOrder()
ByteOrder.BIG_ENDIAN.ByteOrder.BIG_ENDIAN or ByteOrder.LITTLE_ENDIANpublic boolean isMutable()
public boolean isReadOnly()
public boolean contains(byte target)
target - a primitive byte valuepublic int indexOf(byte target)
target in
array. Same as calling indexOf(byte, int) with fromIndex '0'.target - a primitive byte valuei for which array[i] == target, or
-1 if no such index exists.public int indexOf(byte target,
int fromIndex)
target in
array from given start index 'fromIndex'.target - a primitive byte valuefromIndex - search from this indexi for which array[i] == target, or
-1 if no such index exists or fromIndex is gt target length.public int indexOf(byte[] subArray)
target within array, or -1 if there is no such occurrence.
More formally, returns the lowest index i such that java.util.Arrays.copyOfRange(array, i, i + target.length) contains exactly
the same elements as target.
subArray - the array to search for as a sub-sequence of arrayi for which array[i] == target, or
-1 if no such index exists.public int indexOf(byte[] subArray,
int fromIndex)
target within array from given start index 'fromIndex', or -1
if there is no such occurrence.
More formally, returns the lowest index i such that java.util.Arrays.copyOfRange(array, i, i + target.length) contains exactly
the same elements as target.
subArray - the array to search for as a sub-sequence of arrayfromIndex - search from this indexi for which array[i] == target, or
-1 if no such index exists.public boolean startsWith(byte[] subArray)
internal[i] == subArray[i] for i=0..subArray.length-1subArray - to check against the start of the internal arraypublic int lastIndexOf(byte target)
target in
array.target - a primitive byte valuei for which array[i] == target,
or -1 if no such index exists.public boolean endsWith(byte[] subArray)
internal[i] == subArray[i] for i=subArray.length...internal.lengthsubArray - to check against the end of the internal arraypublic boolean bitAt(int bitIndex)
bit value as boolean at the specified index. Bit index 0 is the LSB, so for example byte word
1000 0000 has bitAt(0) == false and bitAt(7) == true.bitIndex - the index of the bit value.IndexOutOfBoundsException - if the bitIndex argument is negative or not less than the length of this array in bits.public byte byteAt(int index)
byte value at the specified index.
An index ranges from 0 to length() - 1. The first char value of the sequence
is at index 0, the next at index 1, and so on, as for array indexing.index - the index of the byte value.byte value at the specified index of the underlying byte array.IndexOutOfBoundsException - if the index argument is negative or not less than the length of this array.public int unsignedByteAt(int index)
byte value at the specified index as an int.
An index ranges from 0 to length() - 1. The first char value of the sequence
is at index 0, the next at index 1, and so on, as for array indexing.index - the index of the unsigned byte value.byte value at the specified index of the underlying byte array as type 4 byte integerIndexOutOfBoundsException - if the index argument is negative or not less than the length of this array.public char charAt(int index)
char value at the specified index.
Reads the primitive from given index and the following byte and interprets it according to byte order.index - the index of the char value.char value at the specified index of the underlying byte array.IndexOutOfBoundsException - if the index argument is negative or length is greater than index - 2public short shortAt(int index)
short value at the specified index.
Reads the primitive from given index and the following byte and interprets it according to byte order.index - the index of the short value.short value at the specified index of the underlying byte array.IndexOutOfBoundsException - if the index argument is negative or length is greater than index - 2public int intAt(int index)
int value at the specified index.
Reads the primitive from given index and the following 3 bytes and interprets it according to byte order.index - the index of the int value.int value at the specified index of the underlying byte array.IndexOutOfBoundsException - if the int argument is negative or length is greater than index - 4public long longAt(int index)
long value at the specified index.
Reads the primitive from given index and the following 7 bytes and interprets it according to byte order.index - the index of the long value.long value at the specified index of the underlying byte array.IndexOutOfBoundsException - if the long argument is negative or length is greater than index - 8public int count(byte target)
target - byte to countpublic int count(byte[] pattern)
Example:
pattern - byte array to countpublic double entropy()
This implementation requires O(n) time and O(1) space complexity.
public Bytes duplicate()
public Bytes byteOrder(ByteOrder byteOrder)
ByteOrder.BIG_ENDIAN.
This option is important for all encoding and conversation methods.
byteOrder - new byteOrderpublic ReadOnlyBytes readOnly()
public ByteBuffer buffer()
ByteBuffer instance.
Changes to it will be directly mirrored in this Bytes instance.
This will honor the set byteOrder().
ReadOnlyBufferException - if this is a read-only instancepublic MutableBytes mutable()
copy() first.MutableBytesReadOnlyBufferException - if this is a read-only instancepublic InputStream inputStream()
public byte[] array()
Modifications to this bytes's content will cause the returned array's content to be modified, and vice versa.
ReadOnlyBufferException - if this is a read-only instancepublic String encodeBinary()
Example: 10011100
public String encodeOctal()
Example: 1124517677707527755
public String encodeDec()
Example: 20992966904426477
public String encodeRadix(int radix)
This is usually a number encoding, not a data encoding (ie. leading zeros are not preserved), but this implementation tries to preserve the leading zeros, to keep the in/output byte length size the same. To preserve the length padding would be required, but is not supported in this implementation.
But still full disclaimer: This is NOT recommended for data encoding, only for number encoding
See Radix Economy and BigInteger.toString(int).
radix - of the String representation (supported are 2-36)public String encodeHex()
Example: 4a94fdff1eafed
public String encodeHex(boolean upperCase)
encodeHex().
Example: 4A94FDFF1EAFED
upperCase - if the output character should be in uppercasepublic String encodeBase32()
Example: MZXW6YQ=
See RFC 4648
@Deprecated public String encodeBase36()
encodeRadix(int) instead; will be removed in v1.0+Base36 (aka Hexatrigesimal) representation. The choice of 36 is convenient in that the digits can be represented using the Arabic numerals 0–9 and the Latin letters A–Z. This encoding has a space efficiency of 64.6%.
Example: 5qpdvuwjvu5
public String encodeBase64()
This encoding is RFC 4648 compatible.
Example: SpT9/x6v7Q==
public String encodeBase64Url()
This encoding is RFC 4648 compatible.
Example: SpT9_x6v7Q==
public String encodeBase64(boolean urlSafe, boolean withPadding)
Example: SpT9/x6v7Q==
urlSafe - if true will substitute '+' and '/' with '-' and '_'withPadding - if true will add padding the next full byte with '='public String encodeUtf8()
public String encodeCharset(Charset charset)
charset - the charset the return will be encodedpublic byte[] encodeUtf8ToBytes()
Similar to encodeUtf8().getBytes(StandardCharsets.UTF_8).
public byte[] encodeCharsetToBytes(Charset charset)
Similar to encodeCharset(charset).getBytes(charset).
charset - the charset the return will be encodedpublic String encode(BinaryToTextEncoding.Encoder encoder)
encoder - the encoder implementationpublic List<Byte> toList()
List collection type
This requires a time and space complexity of O(n).public Byte[] toBoxedArray()
Note: this method was previously called toObjectArray()
public BitSet toBitSet()
BitSet typepublic BigInteger toBigInteger()
BigInteger instance.
If the internal byte order is ByteOrder.LITTLE_ENDIAN, a copy of the internal
array will be reversed and used as backing array with the big integer. Otherwise the internal
array will be used directly.
public UUID toUUID()
UUID instance of the internal byte array. This requires the internal array to be exactly 16 bytes. Takes the first
8 byte as mostSigBits and the last 8 byte as leastSigBits. There is no validation of version/type, just passes the raw bytes
to a UUID constructor.public byte toByte()
If you just want to get the first element as byte, see byteAt(int), using index zero.
IllegalStateException - if byte array has length not equal to 1public int toUnsignedByte()
If you just want to get the first element as byte, see byteAt(int), using index zero.
IllegalStateException - if byte array has length not equal to 1public char toChar()
byteOrder().
If you just want to get the first 2 bytes as char, see charAt(int) using index zero.
IllegalStateException - if byte array has length not equal to 2public short toShort()
byteOrder().
If you just want to get the first 2 bytes as short, see shortAt(int) using index zero.
IllegalStateException - if byte array has length not equal to 2public int toInt()
byteOrder().
If you just want to get the first 4 bytes as int, see intAt(int) using index zero.
IllegalStateException - if byte array has length not equal to 4public int[] toIntArray()
E.g. 4 bytes will be packed to a length 1 int array:
[b1, b2, b3, b4] = [int1]
This conversion respects the internal byte order. Will only work if all bytes can be directly mapped to int, which means the byte array length must be dividable by 4 without rest.
IllegalArgumentException - if internal byte length mod 4 != 0public long toLong()
byteOrder().
If you just want to get the first 4 bytes as long, see longAt(int) using index zero.
IllegalStateException - if byte array has length not equal to 8public long[] toLongArray()
E.g. 8 bytes will be packed to a length 1 long array:
[b1, b2, b3, b4, b5, b6, b7, b8] = [int1]
This conversion respects the internal byte order. Will only work if all bytes can be directly mapped to long, which means the byte array length must be dividable by 8 without rest.
IllegalArgumentException - if internal byte length mod 8 != 0public float toFloat()
byteOrder().IllegalStateException - if byte array has length not equal to 4public float[] toFloatArray()
E.g. 4 bytes will be packed to a length 1 float array:
[b1, b2, b3, b4] = [float1]
This conversion respects the internal byte order. Will only work if all bytes can be directly mapped to float, which means the byte array length must be dividable by 4 without rest.
IllegalArgumentException - if internal byte length mod 4 != 0public double toDouble()
byteOrder().IllegalStateException - if byte array has length not equal to 8public double[] toDoubleArray()
E.g. 8 bytes will be packed to a length 1 double array:
[b1, b2, b3, b4, b5, b6, b7, b8] = [double1]
This conversion respects the internal byte order. Will only work if all bytes can be directly mapped to double, which means the byte array length must be dividable by 8 without rest.
IllegalArgumentException - if internal byte length mod 8 != 0public char[] toCharArray()
String.public char[] toCharArray(Charset charset)
String.charset - to use for decodingpublic int compareTo(Bytes o)
Two byte bytes are compared by comparing their sequences of
remaining elements lexicographically, without regard to the starting
position of each sequence within its corresponding buffer.
Pairs of byte elements are compared as if by invoking
Byte.compare(byte, byte).
Uses ByteBuffer.compareTo(Object) internally.
compareTo in interface Comparable<Bytes>public boolean equals(Object o)
public boolean equals(byte[] anotherArray)
anotherArray - to compare withArrays.equals(byte[], byte[]) returns true on given and internal arraypublic boolean equalsConstantTime(byte[] anotherArray)
This implementation uses the algorithm suggested in https://codahale.com/a-lesson-in-timing-attacks/
anotherArray - to compare withArrays.equals(byte[], byte[]) returns true on given and internal arraypublic boolean equals(Byte[] anotherArray)
null Byte will not be equal to a 0 byteanotherArray - to compare withpublic boolean equals(ByteBuffer buffer)
buffer - to compare withpublic boolean equalsContent(Bytes other)
other - to compare toArrays.equals(byte[], byte[]))public String toString()
Copyright © 2017–2019. All rights reserved.