Get byte[] from List<Byte> [duplicate] - java

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Creating a byte[] from a List<Byte>
I have List list. How to get byte[] ( subarray of list ) from startIndex to endIndex id list ?

List<Byte> theList= new ArrayList<Byte>();
Byte[] your_bytes = theList.subList(startIndex,endIndex).toArray(new Byte[0]);
If finally you need to work with byte (the primitive) then I recommend Apache Commons Collections toPrimitive utility
byte[] your_primitive_bytes = ArrayUtils.toPrimitive(your_bytes);
For most cases you certainly can get by with Byte (object).

ArrayList<Byte> list = new ArrayList<Byte>();
ArrayList<Byte> subList = (ArrayList<Byte>) list.subList(fromIndex, toIndex); //(0,5)
Byte[] array = (Byte[]) subList.toArray();

Well, since the original question actually asks for a sublist containing a byte[] (not Byte[]) here goes:
List<Byte> byteList = .... some pre-populated list
int start = 5;
int end = 10;
byte[] bytes = new byte[end-start]; // OP explicitly asks for byte[] (unless it's a typo)
for (int i = start; i < end; i++) {
bytes[i-start] = byteList.get(i).byteValue();
}

If you need byte[]:
byte[] byteArray = ArrayUtils.toPrimitive(list.subList(startIndex, endIndex).toArray(new Byte[0]));
ArrayUtils.toPrimitive

Related

Convert Arraylist<Object> value in to byte[]

I m trying to get/convert the value of Arraylist in byte[]
below is my code
final ArrayList<Object> imglists = new ArrayList<Object>();
this is my arraylist of Objects in this arraylist m storing the values of images in form of bytes
for (int i=0; i<mPlaylistVideos.size();i++) {
holder.mThumbnailImage.buildDrawingCache();
Bitmap bitmap= holder.mThumbnailImage.getDrawingCache();
ByteArrayOutputStream bs = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, bs);
byte[] rough = bs.toByteArray();
imglists.add(i,rough);
}
I m trying to get the specific value from arraylist and store that in byte[]
this is what I was trying to do
byte[] value=imglists.get(2);
I could not find any complete answer to convert Arraylist of Object into byte[]
I know Arraylist doesn't support primitive datatype (i-e byte)
What you are looking for is a List of byte[], something like that:
List<byte[]> imglists = new ArrayList<>();
Then you can simply add your byte array to your List using the add(E) method as next:
imglists.add(bs.toByteArray());
You will then be able to access to a given byte array from its index in the List using the method get(int) as you try to achieve:
// Get the 3th element of my list
byte[] value = imglists.get(2);
You want to convert ArrayList to byte[] ? or Object to byte[]?
I wrote in this way, just simply convert the element in ArrayList into byte[] ,it works!
List<Object> objects = new ArrayList<Object>();
objects.add("HelloWorld".getBytes());
byte[] bytes = (byte[]) objects.get(0);
System.out.println(new String(bytes)); // HelloWorld

Save bits in a stream of bytes in Android Java?

I need to save a binary stream, that I will later convert to text. Since binary streams don't exist in Java, I just saved my 'bits' in a stream of 'bytes' just to test my code. Now I have a stream of bytes where 1 bit is encoded on 1 byte.
byte [] stream = new byte [1500];
int str = 0;
byte [] data = new byte [1];
for (int i = 0; i<original.cols(); i++)
{
for (int j= 0; j<original.rows(); j++)
{
original.get(j,i, data);
if ((data[0]==0))
{
stream [str]=0;
str = str+1;
}
else
{
stream [str]=1;
str = str+1;
}
}
}
Can anyone help me to properly save my bits encoded in a stream of bytes, where 1 byte would represent 8 bits ?
A java.util.BitSet contains helper methods for dealing with raw bits, and conversions to and from byte arrays. In the following example, bytes will contain a single byte:
int numberOfBits = 8;
BitSet bitSet = new BitSet(numberOfBits);
bitSet.set(3, true);
bitSet.set(7, true);
byte[] bytes = bitSet.toByteArray();

Siphash tostring and getBytes()

I have generated SipHash for 1 string and 2 long values (for many such combinations of string and long). I used -
Hasher hash = Hashing.sipHash24().newHasher().putUnencodedChars("abcd").putLong(123).putLong(123);
Now I converted this hash to string using -
String hashString = hash.hash().toString();
But, I wanted the bytes array of the string, Could there be any way, so that I am able to get the bytes array from this string same as to the one I would have got from byte[] hashBytes = hash.hash().asBytes(); I wanted to convert the string I had got from these hashes to bytes array.
Actually I realised that the bytes array was using only 8 bytes of space for the siphash, where as the length of string was 18 bytes. So , I guess storing the hash as bytes array would be more optimised.
BaseEncoding.base16().lowerCase().decode(string)
should convert HashCode.toString() back into the byte array you would've gotten from asBytes().
You can parse the string back into a HashCode instance with HashCode.fromString(string). Then you can call .asBytes() on the HashCode instance to get back a copy of the underlying byte[].
So basically you want:
byte[] bytes = HashCode.fromString(string).asBytes();
Here is the code to get bytes array from string -
public static byte[] getBytes(String hashString) {
final byte[] bytes = new byte[8];
HashMap<Character, String> bin = new HashMap<>();
bin.put('0', "0000");
bin.put('1', "0001");
bin.put('2', "0010");
bin.put('3', "0011");
bin.put('4', "0100");
bin.put('5', "0101");
bin.put('6', "0110");
bin.put('7', "0111");
bin.put('8', "1000");
bin.put('9', "1001");
bin.put('a', "1010");
bin.put('b', "1011");
bin.put('c', "1100");
bin.put('d', "1101");
bin.put('e', "1110");
bin.put('f', "1111");
for (int i = 0; i < 16 && i < hashString.length(); i += 2) {
final BitSet bitset = new BitSet(8);
String byteBinary = bin.get(hashString.charAt(i)) + bin.get(hashString.charAt(i + 1));
for (int j = 0; j<8; j++) {
if (byteBinary.charAt(j) == '1')
bitset.set(7-j, true);
else
bitset.set(7-j, false);
}
bytes[i/2] = bitset.toByteArray()[0];
//System.out.println(byteBinary);
}
return bytes;
}

Conversion from Arraylist<Byte> to byte array in android

I have a arraylist of Bytes and i am converting them into a byte array.I have used the following method.However it gives me the following error:
E/AndroidRuntime(5228): java.lang.NoClassDefFoundError: com.google.common.primitives.Bytes
ArrayList<Byte> byteArrayList_song=new ArrayList<Byte>();
byte[] bytes_song_byte;
for(int i=0;i<int_arraylist.size();i++)
{
bytes_song_byte=Bytes.toArray(byteArrayList_song);
}
Looks like Google Guava is not on your class path, also you should remove the for loop from the above code, as that is what the Guava function does for you.
ArrayList<Byte> byteArrayList_song = new ArrayList<Byte>();
byte[] bytes_song_byte = Bytes.toArray(byteArrayList_song);
You can do this conversion without external libs
byte[] bytes_song_byte = new byte[byteArrayList_song.size()];
for (int i = 0; i < byteArrayList_song.size(); i++) {
bytes_song_byte[i] = byteArrayList_song.get(i);
}
note that if byteArrayList_song has any null elements this code will throw a NullPointerException
Try the following
ArrayList<Byte> byteArrayList_song=new ArrayList<Byte>();
byte[] bytes_song_byte;
bytes_song_byte=byteArrayList_song.toArray(new Byte[byteArrayList_song.size()]);

How to Convert an int ByteStream to a String?

Hi I am trying to implement the interface SourceStream in my application and overrides the method read(byte[],off,len) and I read the bytes from a server.But I want to convert those byte stream into String for that I used a string object by new String(byte[]) but it asks the initial byte in off and length of the bytes ie len as parameters..Why it is asking like that, as we contain only Strring(bye[])only. can any one help me...Thanks
If you just have a byte[] then you can create a new String via the String(byte[],int,int) constructor provided by the API.
In your case you would do
byte[] myBytes = ("Hello, World!").getBytes();
String myString = new String(myBytes, 0, myBytes.length);
System.out.println(myString);
EDIT:
Try something like this:
int readLength = (len > bufSize ? bufSize : len);
for (int i = 0; i < readLength; i++) {
b[off + i] = buffers[PBuf][PByte];
}
String metaSt = new String(b, 0, readLength);
Just provide 0 as the initial offset and yourArray.Length as the length and you're done. Quite why a method that takes just a byte array isn't provided is anyones guess - probably just to avoid 101 variations of the method.

Categories