Hi there
I'm trying to understand a piece of code that reads a long value from a byte array at a given position, but I don't know enough about bit shifting, LSB, MSB etc., to fully understand it. It seems to have been overcomplicated a bit, which doesn't help.
I need you to try and simplify it, and explain what the code does.
I have a byte array containing this data (in hex: 128 bits * 2):
34b7ee402d980200e08f841441702912000005f4697a0108220254001c00fcd6
The function gets called like this:
int pos = 0;
long ret;
ret = [login to view URL](32);
[login to view URL]([login to view URL]("%s (%s:%s)", ret, [login to view URL](ret), [login to view URL](ret)));
pos += 32;
// skip some positions
pos += 8;
// skip some positions
pos += 88;
// skip some positions
pos += 16;
ret = [login to view URL](6);
[login to view URL]([login to view URL]("%s (%s:%s)", ret, [login to view URL](ret), [login to view URL](ret)));
pos += 6;
Output. Please make sure your function can handle reading 6 bits, and not always entire bytes (as it also does now):
1089386292 (1000000111011101011011100110100:40eeb734)
5 (101:5)
The function is here:
private long getLongFromPos(int length) {
int sByte, eByte, cByte, sBit, eBits, mask;
long r;
r = 0;
sByte = pos/8; // get start byte
eByte = (pos+length)/8; // get end byte
cByte = sByte;
sBit = pos % 8; // Find what bit to start on
eBits = (pos + length) % 8; // number of bits to read for last byte
// process first byte
mask = (0xFF << sBit) & 0xFF;
if(sByte == eByte) {
mask = (0xFF >> 8-eBits) & mask;
return (bytes[sByte] & mask) >> sBit;
}
r = (bytes[sByte] & mask) >> sBit;
// build up long from whole bytes
int bPos = 1;
for(int i = sByte+1; i < eByte; i++) {
r = ((long)(bytes[i] & 0xFF) << ((bPos*8)-sBit)) | r;
bPos++;
}
// add last bits
if(0 == eBits) // if there is zero bits left to read we are done
return r;
else
mask = (0xFF >> (8-eBits));
r = ((long)(bytes[eByte] & mask) << ((bPos*8)-sBit)) | r;
return r;
}
Thank you :-)
Let me know if questions, and sorry if the formatting is bad .. I don't see an option to format it here.
I can definitely trim this down for you, and put some more thoughtful comments in the thing to explain what's happening, even document an example run with data values. When do you need this completed by?
Hello Sir,
I have been workin as a java software engineer for 5 years. i can simply explain you what this code does. Let me know if you are intrested in working with me. Thanks
I am dealing this type of situation from quiet long in my project. I am good in debugging the code and making changes in it.
i am working as a java developer in amdocs and having very good experience. As this is my first freelancer project so i am bidding quiet low.
i had worked on stegenograpy tool and many other project that helps me to understand bit manipulation in java