简体   繁体   中英

Add Nibble to an array of bytes

I have an array of 9 bytes in Java but my function need to return an array of size 10. The difference I need to pad with Nibbles.

If a nibble is a half of a byte, can I simply add a (byte) 0 to an array at the end or adding 2 nibbles instead will make a difference? Is there a difference between 2 nibbles and a (byte) 0 in this case?

So your question is if nibble 0000 adjacent to nibble 0000 equals byte 00000000 ?

Yes.

When you write down the individual bits like that it should be obvious I think.

The need for padding with partial bytes will only arise when you are storing data with partial bytes. For example, let's assume I limited my character set to only az, AZ, 0-9, and the space character. That would enable me to use only 4 bits to encode each character.

If a nibble is a half of a byte, can I simply add a (byte) 0 to an array at the end or adding 2 nibbles instead will make a difference?

Is there a difference between 2 nibbles and a (byte) 0 in this case?

No there is no difference since a byte (8 bits) is made up 2 x nibble (4 bits).

Can I even put 8.5 bits into an array of bytes and then check the array for "length" and get back 8.5 as value?

For 8.5 bits? At this point it will be returned as length of 2 bytes. If you mean 8.5 bytes then it's returned as 9 bytes.

Remember The smallest data-type is a byte not a nibble !! By declaring a type byte (even with no value assigned) you've automatically made 8 bits of 0000 0000 . Nibbles just make it easier to visualize the bits within a byte's value (when written in hex notation).

For example the single byte value 0xF0 can be visualised as two nibbles of 1111 0000 . Now for a byte 0xBA , if you wanted just one nibble you'll have to make the byte as either 0x0B or 0x0A ...

I have an array of 9 bytes in Java but my function need to return an array of size 10. The difference I need to pad with Nibbles.

Your function returns 80 bits. With 9 bytes you'll have a total 72 bits so you pad with extra 8 bits which means add one byte extra of zero value (eg: 0x00 ).

  • In the case of some 8 & half bytes, you should actually create 9 bytes (72bits) but only update the first 68 bits (8.5 bytes).

  • Best logic is to just declare a byte array with length of 10 ( ie: 80 zero bits). Then you can update as many or as few bits as you need within this total allocated space.
    This way "I have an array of 9 bytes" becomes "I create an array of 10 bytes and only update 9 or even 8.5 bytes" which leaves you with automatic padding of those unused 1 or 1.5 bytes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM