Judging by the "Want to read a value as ..." comment where 0 512 88
was desired, it looks to me like you have 3 different fields split across 4 bytes. The only practical way I can see how to get the desired numerical results from the original data is to manipulate the bytes as follows:
- Rotate right (with wrap) the 1st 2 bytes
- Rotate left (with wrap) the 2nd 2 bytes
- Combine the data
- Isolate the 3 individual fields from the combined result
It may be possible to optimize this, but here’s an implementation based on the above assumptions:
-- Rotate the 1st 2 bytes to the right and the 2nd 2 bytes to the left
local x = 0x00208005
local x_hi = bit.rshift(bit.band(x, 0xffff0000), 16)
local x_lo = bit.band(x, 0x0000ffff)
local x_hi_ror = bit.bor(bit.ror(x_hi, 4), bit.lshift(bit.band(x_hi, 0x000f), 12))
local x_lo_rol = bit.bor(bit.band(bit.rol(x_lo, 4), 0x0fff), bit.rshift(x_lo, 12))
local x_new = bit.bor(bit.lshift(x_hi_ror, 16), x_lo_rol)
print("x = " .. string.format("0x%04x", x) .. "\n" ..
"x[1] = " .. bit.rshift(bit.band(x, 0xff000000), 24) .. "\n" ..
"x[2] = " .. bit.rshift(bit.band(x, 0x00ffff00), 8) .. "\n" ..
"x[3] = " .. bit.band(x, 0x000000ff))
print("x_new = " .. string.format("0x%04x", x_new) .. "\n" ..
"x_new[1] = " .. bit.rshift(bit.band(x_new, 0xff000000), 24) .. "\n" ..
"x_new[2] = " .. bit.rshift(bit.band(x_new, 0x00ffff00), 8) .. "\n" ..
"x_new[3] = " .. bit.band(x_new, 0x000000ff))
Refer to the Lua Bit Operations Module for more information on the bit operations used in this example.
NOTE: If this answer is based on faulty assumptions and doesn't help solve your problem, then you'll have to provide more information.
Can you add an illustration of what you mean, e.g.
or something else?
You could accumulate the nibbles by multiplying, e.g.
local byte = LoNibble + HiNibble * 16
.Below is the capture: 00000000001000001000000000000101 = 0x00 0x20 0x80 0x05 Want to read a value as: 00000000001000000000000001011000 = 0 512 88
So, is there a way to rearrange it and then read it?
Not sure I follow, you have:
and you want it to be:
How are the nibbles rearranged there? You seem to have swapped the last two nibbles and then 4th and the last.
There would seem to be a typo as 0 512 88 would be
0x00 0x02 0x00 0x58
and not0x00 0x20 0x00 0x58
. Is that what was intended?