Convert Byte [] to UnsignedByte []
I want to optimize the following java code (one method):
private static UnsignedByte[] getUnsignedBytes(byte[] bytes){
UnsignedByte[] usBytes = new UnsignedByte[bytes.length];
int f;
for(int i = 0; i< bytes.length;i++){
f = bytes[i] & 0xFF;
usBytes[i] = new UnsignedByte(f) ;
}
return usBytes;
}
This code basically converts a byte array (which is a file) to an UnsignedByte array so that it can be sent to a web service that I am consuming on the apache axis.
Is there a way to avoid this for the loop. Is there any direct method for doing this?
Thank.
+3
source to share
2 answers
I would do it with Guava this way:
UnsignedByte[] usBytes = Lists.transform(Arrays.asList(bytes), new Function<UnsignedByte, Short>() {
@Override
public UnsignedByte apply(@Nullable Byte input) {
f = input & 0xFF;
return new UnsignedByte(f) ;
}
}).toArray(new UnsignedByte[bytes.length]);
+1
source to share