lua-users home
lua-l archive

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


Am 08.12.2013 19:57 schröbte Philipp Janda:

This looks like there's some truncation to 32 bits going on. Can you
check if recompiling with ´STRUCT_INT` #defined to `ptrdiff_t` solves
the problem (the default `long` still being 32 bits on Windows 64)?


Actually, this seems to be a general problem for integer types larger than `STRUCT_INT`:

    print( -2, tohex( int2str( -2, 16 ) ) )
    print( -2, tohex( struct.pack( '>I16', -2 ) ) )
    print( -2, tohex( struct.pack( '>i16', -2 ) ) )
    print( "2^64", tohex( int2str( 2^64, 16 ) ) )
    print( "2^64", tohex( struct.pack( '>I16', 2^64 ) ) )
    print( "-(2^64)", tohex( int2str( -(2^64), 16 ) ) )
    print( "-(2^64)", tohex( struct.pack( '>I16', -(2^64) ) ) )


-2	FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FE
-2	00 00 00 00 00 00 00 00 FF FF FF FF FF FF FF FE
-2	00 00 00 00 00 00 00 00 FF FF FF FF FF FF FF FE
2^64	00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00
2^64	00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
-(2^64)	FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00
-(2^64)	00 00 00 00 00 00 00 00 80 00 00 00 00 00 00 00


Philipp

#!/usr/bin/lua

local struct = require( "struct" )

local function BE( s, b )
  return b .. s
end

local function LE( s, b )
  return s .. b
end

local function int2str( number, bytes, b_order )
  b_order = b_order or BE
  number = math.floor( number )
  local neg = number < 0
  if neg then number = -number end
  local carry = neg and 1 or 0
  local s = ""
  for i = 1, bytes do
    local d = math.floor( number/256 )
    local b = number - d*256
    if neg then
      s = b_order( s, string.char( bit32.band( bit32.bnot( b )+carry, 255 ) ) )
      if b ~= 0 then carry = 0 end
    else
      s = b_order( s, string.char( b ) )
    end
    number = d
  end
  return s
end

local function tohex( s )
  local t = {}
  for i = 1, #s do
    t[ i ] = ("%02X"):format(  s:byte( i ) )
  end
  return table.concat( t, " " )
end


assert( int2str( 10, 4 ) == struct.pack( '>I4', 10 ) )
assert( int2str( 10, 4, LE ) == struct.pack( '<I4', 10 ) )
assert( int2str( -1, 4 ) == struct.pack( '>I4', -1 ) )
assert( int2str( -2, 4 ) == struct.pack( '>i4', -2 ) )
print( -2, tohex( int2str( -2, 16 ) ) )
print( -2, tohex( struct.pack( '>I16', -2 ) ) )
print( -2, tohex( struct.pack( '>i16', -2 ) ) )
print( "2^64", tohex( int2str( 2^64, 16 ) ) )
print( "2^64", tohex( struct.pack( '>I16', 2^64 ) ) )
print( "-(2^64)", tohex( int2str( -(2^64), 16 ) ) )
print( "-(2^64)", tohex( struct.pack( '>I16', -(2^64) ) ) )