User File #67926325655324243

Upload All User Files

#67926325655324243 - byterange_decode

byterange_decode.lua
341 downloads
Uploaded 12/7/2020 1:32 AM by CoolHandMike (see all 27)
brunovalads' byterange_decode in a runnable format.
function byterange_decode(values, size, big_endian, signed)
--special thanks to brunovallads
--syntax: raw = memory.readbyterange(); data = raw:byterange_decode(4);
  -- Error handling
  if type(values) ~= "table" then print("Insert correct memory.byterange table!") ; return end
  if not size or size < 1 or size > 6 then print("Insert correct size value! Can accept values between 1 and 6.") ; return end
  if size > #values+1 then print("Size is bigger than the memory.byterange table!") ; return end -- +1 due table 0 indexed
  
  local output = {}
  
  for i = 0, (math.floor((#values+1)/3)*3-1), size do
    
    local out_value = 0
    
    -- Loop to correctly calculate the number based on the endianess
    for j = 0, size-1 do
      if big_endian then
        out_value = out_value + values[i+j]*(0x100^(size-1-j))   -- {AA, BB} -> AA00 + BB = AABB
      else
        out_value = out_value + values[i+j]*(0x100^j) -- {AA, BB} -> AA + BB00 = BBAA
      end
    end
    
    -- Check signedness
    if signed then
      local maxval = (0x100^size)/2
      if out_value >= maxval then out_value = out_value - 2*maxval end
    end
    
    output[i/size] = out_value
  end
  
  if (#values+1)%size ~= 0 then print(string.format("%d byte(s) left, due to the selected size or memory.byterange size!", (#values+1)%size)) end -- +1 due table 0 indexed

  return output
end

	
while true do
	local length = 64
	local decoded_bytes = byterange_decode(memory.readbyterange(0x100, length), 2, false, false);
	for i = 0, length-1 do
		gui.text(0,16*i,decoded_bytes[i])
	end
    emu.frameadvance();
end