lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On 16-07-03 03:23 AM, Niccolo Medici wrote:
> Hi!
> 
> For a calculator I'm writing, that can display integers in hex/binary,
> I want to display the hex (or binary) machine representation of
> *negative* integers as well. The prevalent representation of negative
> integers is known as "two's complement", but I don't at all care if
> the Lua engine is running on a machine that uses some other
> representation and that my calculator shows something other that 2's
> complement in this case.
> 
> In Lua 5.1 and Lua 5.3 the solution is ridiculously simple:
> 
>     -- Lua 5.1
>     > print(("%x"):format(-123456))
>     fffe1dc0
> 
>     -- Lua 5.3
>     > print(("%x"):format(-123456))
>     fffffffffffe1dc0
> 
> This is perfect for me! (Converting this to binary is a simple and
> efficient matter: by doing string replacement.) But, unfortunately, in
> Lua 5.2 it fails:
> 
>     -- Lua 5.2
>     > print(("%x"):format(-123456))
>     stdin:1: bad argument #1 to 'format' (not a non-negative number in
> proper range)
> 
> Is there a solution that works in 5.2 as well?
> 
print(('%x'):format(bit32.band(-2)))