lua-users home
lua-l archive

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


On 5/15/19, Coda Highland <chighland@gmail.com> wrote:
> However, the way the spec is written, the conversion of a negative signed
> number into an unsigned integer is done by repeatedly adding or subtracting
> one more than the maximum value of the destination type until the value is
> in range. This means that if you start with -1 (which is out of range for
> uint64_t) you have to add ULONG_MAX+1 repeatedly until the value DOES fit.
> This is independent of the underlying bit pattern of the number, whether
> it's 2's complement, 1's complement, or sign-magnitude. This means that
> regardless of how the compiler/CPU implements it, (uint64_t)-1 MUST be
> equal to ULONG_MAX.

> On a 2's complement machine, this is just a sign extension: copy the most
> significant bit into all of the new bits of the larger type. The same
> operation works when casting int32_t to int64_t or to uint64_t.

> On a 1's complement machine or a sign-magnitude machine, casting to int64_t
> and uint64_t are different operations. Casting to int64_t on 1's complement
> is a sign extension, and on a sign-magnitude machine you have to copy the
> old sign bit into the new sign bit and set the old one to zero. Either way,
> the resulting value is -1LL, as the spec demands. Casting -1 to uint64_t is
> NOT just casting to int64_t and then reinterpreting the bit pattern like it
> is on a 2's complement machine. Because the spec demands that it must be
> equivalent to adding ULONG_MAX+1, you have to do a sign extension and then
> add 1 if you're using a 1's complement machine, and if you're using a
> sign-magnitude machine it's a bitwise negation followed by setting the sign
> bit (back) to 1.

thanks for clarifying, i did not see why

lua_Unsigned umax = -1 ;

is fine here and hence used the

lua_Unsigned umax = ~ (lua_Unsigned) 0 ;

solution since it was easier to understand how it works.
but both are correct.

a LUA_UNSIGNED_MAX preprocessor macro in the Lua headers
could not hurt, though.