1

I was trying to convert an parcelable object into byte array, and in my class I have a byte type value. But when I marshal it using parcelable single byte is allocated 4 bytes in byte array. And in code I found parcel.writeByte internally call writeInt. Is there any way I can write a single byte into parcelable ?

Any help appreciated.

upv
  • 539
  • 5
  • 7
  • 15
  • no, even if you want to write a boolean value (that is one bit) using `writeValue` an integer is written into a `Parcel` – pskink Feb 09 '17 at 06:39
  • @pskink That shouldn't be an issue, though. http://stackoverflow.com/questions/6201311/how-to-read-write-a-boolean-when-implementing-the-parcelable-interface#7089687 – OneCricketeer Feb 09 '17 at 07:35
  • @cricket_007 still 4 bytes are written – pskink Feb 09 '17 at 07:36
  • @upv could you explain, why exactly do you need that? Storing a single byte is not advantageous from memory or performance perspective: all modern hardware is optimized for 32bit, so manipulating values of smaller size may actually be a bit *slower*. Also most Buffers/arrays etc. including parcel storage itself are most likely going to be aligned by 4+ bytes, so if you store <4 bytes at once, some space will still be wasted… – user1643723 Feb 09 '17 at 07:42

1 Answers1

1

AFAIK, writing less than 4 bytes to Parcel is not possible with any currently available public API.

If you have up to 4 bytes, you can use ByteBuffer/bit shift to store them in the single integer value. You can also store arbitrary number of bytes (including a single byte) in a byte array. Doing so allows you to achieve any desirable memory layout, but incurs overhead of extra 4 bytes to store the array length.

user1643723
  • 4,109
  • 1
  • 24
  • 48