tags:

views:

121

answers:

1

Using VBA I am loading an 8-byte floating point number from an array of bytes into a Double. Some numbers will be IEEE 754 NaN (i.e. if you try to print it with Debug.Print you will see 1.#QNAN). My question is, how can I test whether the data contained in the Double is an NaN as opposed to a regular number?

Thanks.

+2  A: 

NaN's have a pattern in the exponent that you can identify while they're still in the byte array. Specifically, any NaN will have an exponent of all 1's, as will any Infinity, which you probably also should trap.

In a double, the exponent is in the highest-order two bytes:

 SEEEEEEE EEEEMMMM MMM....

Assume those are b(0) and b(1):

  Is_A_Nan = ((b(0) And &H7F) = &H7F) And ((b(1) And &HF0) = &HF0)

That's air code, but you get the idea.

If you need to distinguish between SNaN, QNaN, and Infinity you'll need to look deeper, but it doesn't sound like that's an issue for you.

Jim Mack
I should note that if the bytes are in the opposite order, substitute b(6) for b(1), and b(7) for b(0) above...
Jim Mack
Thanks Jim, this worked perfectly. I also tested this with a 4-byte Single, in which case it seemed like it was only necessary to test the first byte.
Abiel
Jim Mack