sr01853
sr01853

Reputation: 6121

Confusing byte array

I have seen a proper byte array initialization as say

byte[] a = new byte[8];

But what does this mean?

byte[] bitfield = new byte [0xFFFFFFF/8];
n = 18;  // some integer
bitfield [n / 8] |= 1 << (n % 8);

Please also explain what does 0xFFFFFFF/8 means here.

Upvotes: 2

Views: 233

Answers (3)

Katona
Katona

Reputation: 4901

Simply put, and without going into details, that construct is representing a bitset with a byte array which allows random access to the individual bits based on their position.

Upvotes: 0

nanofarad
nanofarad

Reputation: 41271

0xFFFFFFF/8

is simply a value(268435455) divided by 8, initializing the array to that size(truncated, of course).

At the next step we get n and set element n/8, or 2 due to truncation, to be that same element with a bitwise OR to 1<<(n%8) or 1 shifted left (n%8) bits. This is equivalent of:

bitfield[n/8] = bitfield[n/8] | (1 << (n % 8))

Notice that 1<<(n%8) is equal to 2^(n%8) where (n%8) is the remainder when n is divided by 8.

Upvotes: 2

Code-Apprentice
Code-Apprentice

Reputation: 83527

0xFFFFFFFF is an integer literal in hexadecimal. Then it is divided by 8.

Upvotes: 0

Related Questions