Is there something like bytes(byte...b):byte[]?
i am looking fo开发者_StackOverflow中文版r a simple method were i can pass in some bytes, as varargs, and get a byte[] returned, like:
static byte[] byteArray(byte ...bytes){ return bytes;}
What i found so far...
java.lang.Byte
doesn't have it
java.util.Arrays
doesn't have it
com.google.common.primitives.Bytes.toArray(..)
want a Collection
sample use case: assertThat(actualArray,is(byteArray(1,2,3,4,5)));
There is no function for that because
new byte[]{1,2,3,4,5}
is also quite short.
Edit: Please note that any helper method like this
static byte[] toBytes(byte ... bytes)
{
return bytes;
}
has the same problem as new byte{...}
: All arguments must be real bytes and not propagated to int
. So arguments like 0xca
must be casted to byte
in both cases:
byte ba1[] = new byte[]{ (byte)0xca };
byte ba2[] = toBytes( (byte)0xca );
If you want easier input then you must write a custom method which allocates a byte array and do the coping and casting by hand.
If you're assigning the bytes to a variable or field of type byte[]
, you can write this even more compactly than new byte[]{1, 2, 3, 4}
:
byte[] bytes = {1, 2, 3, 4};
Also, the problem with 0xca, 0xfe, 0xba, 0xbe
is that all of those values are actually outside the legal range for a Java byte
, since byte
in Java is signed by default.
Perhaps you want a method that takes an argument of type long...
and returns a byte[]
, using UnsignedBytes.checkedCast or UnsignedBytes.saturatedCast to convert each value.
精彩评论