Ask Your Question
0

LUA: byte to nibbles (low/high)

asked 2021-09-07 13:49:21 +0000

sezb51 gravatar image

Hello,

I need to convert raw hex data: "10 55 55 59 93 09 22 f0" into string: "0f22903995555501" but how to extract high/low nibbles from individual byte ?

function userdata2bcd(buffer, offset, len)
  local bytearr = {}
  for i = 1, len do
    num = userdata2dec(buffer, offset+len-i, 1)
    highByte = ...
    lowByte  = ...
    bytearr[i] = tostring(lowByte) .. tostring(highByte)
  end
  return table.concat(bytearr)
end

Any suggestion is appreciated...

Thx, A!

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2021-09-07 15:06:17 +0000

hugo.vanderkooij gravatar image

updated 2021-09-07 15:07:44 +0000

I am not a LUA expert. But in the good old days of 8 bit assemblers it was a matter of masking and bitshift action. That migh help you to search in the right direction.

A pointer like http://lua-users.org/wiki/BitwiseOper... might help there.

edit flag offensive delete link more

Comments

this looks indeed promising:

function userdata2bcd(buffer, offset, len)
  local bytearr = {}
  for i = 1, len do
    num = userdata2dec(buffer, offset+len-i, 1)
    highByte = bit.rshift(num, 4)
    lowByte  = num - highByte * 16
    bytearr[i] = string.format("%.1X", lowByte) .. string.format("%.1X", highByte)
  end
  return table.concat(bytearr)
end

it does work indeed.

Thx,

sezb51 gravatar imagesezb51 ( 2021-09-07 17:28:16 +0000 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

Stats

Asked: 2021-09-07 13:49:21 +0000

Seen: 59 times

Last updated: Sep 07