Package com.globalmentor.java
Class Bytes
java.lang.Object
com.globalmentor.java.Bytes
Utilities for manipulating bytes.
- Author:
- Garret Wilson
-
Field Summary
Fields -
Method Summary
Modifier and TypeMethodDescriptionstatic byte[]
Converts a sequence of hex values to bytes, without regard to case.static byte[]
generateRandom
(int length) Creates an array of random bytes.static byte[]
generateRandom
(int length, Random random) Creates an array of random bytes.static boolean
startsWith
(byte[] bytes, byte[] prefix) Determines if the given byte array starts with the specified prefix.static String
toHexString
(byte[] bytes) Converts an array of bytes into a lowercase hex string, with each character pair representing the hexadecimal value of the byte.
-
Field Details
-
NO_BYTES
public static final byte[] NO_BYTESA shared empty array of bytes.
-
-
Method Details
-
toHexString
Converts an array of bytes into a lowercase hex string, with each character pair representing the hexadecimal value of the byte.- Parameters:
bytes
- The values to convert.- Returns:
- A lowercase string with hexadecimal digits, each pair representing a byte in the byte array.
- See Also:
-
fromHexString
Converts a sequence of hex values to bytes, without regard to case.- Implementation Note:
- This implementation modified from an answer on Stack Overflow.
- Parameters:
hex
- The two-digit hex values to convert.- Returns:
- The equivalent bytes of the hex characters.
- Throws:
IllegalArgumentException
- if a hex value is missing one of its pairs (i.e. the sequence length is odd) or if a hex representation contains an invalid character.- See Also:
-
generateRandom
Creates an array of random bytes.- Implementation Specification:
- This implementation delegates to
generateRandom(int, Random)
using a defaultRandom
instance. - Parameters:
length
- The number of bytes to create.- Returns:
- A new array of the given length filled with random bytes.
- Throws:
IllegalArgumentException
- if the given length is negative.- See Also:
-
generateRandom
Creates an array of random bytes.- Parameters:
length
- The number of bytes to create.random
- The random number generator to use.- Returns:
- A new array of the given length filled with random bytes.
- Throws:
NullPointerException
- if the given random number generator isnull
.IllegalArgumentException
- if the given length is negative.- See Also:
-
startsWith
public static boolean startsWith(byte[] bytes, byte[] prefix) Determines if the given byte array starts with the specified prefix. Neither byte array is modified by this method.- Parameters:
bytes
- The bytes being examined.prefix
- The prefix to compare with the given bytes.- Returns:
- Whether the given bytes start with the specified prefix.
-