Reputation: 23587
I am trying to understand a piece of code but not able to get clear idea about few points here is the Java code
private String firstMethod(int number){
return secondMethod(number >> 16 & 0xFF, 0).concat(secondMethod(number >> 8 & 0xFF, 1)).concat(secondMethod(number & 0xFF, 7));
}
private static String secondMethod(int value, int offset)
{
return thirdMethod(value >> 4, offset).concat(thirdMethod(value & 0xF, offset + 4));
}
private static String thirdMethod(int value, int offset)
{
String chars = getAlphabet();
int pos = (value + offset) % 16;
return chars.substring(pos, pos + 1);
}
value passed to firstMethod
is a random number for first time and all subsequent call to method will pass value incremented by 1.
I am clear about bit-wise right shift operation as well about the use of & 0xFF
, however I am still not very clear about following points
Can anyone help me to understand those 2 point
Upvotes: 3
Views: 1341
Reputation: 11
An integer is a 32-Bit Number.
So as a binary-number, you can represent number as:
XXXXXXXXAAAAAAAABBBBBBBBCCCCCCCC (X, A, B, C stands for 0 or 1).
number >> 16 gives you XXXXXXXXAAAAAAAA. number >> 16 & 0xFF gives you AAAAAAAA
By the firstMethod number is splited in 3 Bytes:
AAAAAAAA and BBBBBBBB and CCCCCCC (Shift of 16, shift of 8 and no shift) and given to the secondMethod.
In the secondMethod the 8 Bits are splited in the higher four bits and the lower four bits.
In the thirdMethod the four Bits is translate to a String containing one char.
But the sense depends on "getAlphabet()". Perhaps there will be also a usefull interpretation for the offset.
So you have to give further information!
Upvotes: 1
Reputation: 533530
Shifting given value by specific number (like 16 and 8 for first than no sift etc)
You are printing bytes as hexi-decimal. Each byte is 8-bits so you want to shift each byte by
Not clear about use of offset ,specifically passing certain number as offset.
I am pretty sure the offset is either a) incorrect, b) a really obscure way of masking/encoding the data.
To print a number as a 6 byte hexi-decimal String you can do this.
System.out.println(String.format("%06x", 12345));
prints
003039
This is much shorter. ;)
>>
has a surprising low precedence. This means
number >> 16 & 0xFF
is actually
number >> (16 & 0xFF)
or
number >> 16
what you indedn was
(number >> 16) & 0xFF
or as the result is unsigned.
(number >>> 16) & 0xFF
Upvotes: 3