Re: ffi.cast: weird behaviour

  • From: Mike Pall <mike-1206@xxxxxxxxxx>
  • To: luajit@xxxxxxxxxxxxx
  • Date: Wed, 27 Jun 2012 00:04:57 +0200

Wolfgang Pupp wrote:
> I've recently been surprised by weird (IMHO) behaviour of ffi.cast;
> Consider this code:
> 
> local ffi = require'ffi'
> local zeroneg = '\x00\x00\x00\x80'
> local nan = '\xff\xff\xff\xff'
> 
> print(ffi.cast('float *', zeroneg)[0])
> print(ffi.cast('float *', nan)[0])
> 
> I would have expected this to print -0 and nan. But it doesn't. I get
> -0 and *nil* instead.

LuaJIT reserves certain NaN bit patterns for itself. Your cast and
the following conversion to a double creates one of these reserved
patterns (which happens to map to nil).

> Am I doing it wrong in the first place?

Only use the canonical NaN bit patterns: ffc00000 for floats and
fff80000 00000000 for doubles. Or the positive equivalents on
non-x86 platforms (but the sign bit doesn't matter for NaNs).

--Mike

Other related posts: