Would it be safe just checking the type after this operation? e.g. function read_float(s) local x = ffi.cast("const float*",s)[0] if type(x) ~= "number" then x = 0/0 end return x end print(read_float("\xff\xff\xff\xff")) I ask as I've written various parsers that I've only just realised do this unsafely. The alternative is to check that the string does not contain an invalid NaN upfront: what would this look like? D P.S; any chance we'll see you (Mike Pall) at the lua workshop this weekend in Toulouse, France? On 27 June 2012 00:04, Mike Pall <mike-1206@xxxxxxxxxx> wrote: > 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 > >