Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

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.