# CSharp - double.NaN(倍精度浮動小数のNaN) のバイト列判定 ###### tags: `C#`, `.net` ~~~cs using System.IO; using System.Runtime.InteropServices; [StructLayout(LayoutKind.Explicit)] public struct NaNData { [FieldOffset(0)] public float floatValue; [FieldOffset(0)] public double doubleValue; [FieldOffset(0)] public byte byte0; [FieldOffset(1)] public byte byte1; [FieldOffset(2)] public byte byte2; [FieldOffset(3)] public byte byte3; [FieldOffset(4)] public byte byte4; [FieldOffset(5)] public byte byte5; [FieldOffset(6)] public byte byte6; [FieldOffset(7)] public byte byte7; } class Program { static void Main(string[] args) { NaNData nan = new NaNData(); nan.byte0 = 0; // f!=0 nan.byte1 = 0; // f!=0 nan.byte2 = 1; // f!=0 nan.byte3 = 0; // f!=0 nan.byte4 = 0; // f!=0 nan.byte5 = 0; // f!=0 nan.byte6 = 0b1111 << 4; //BIT52-55 e=2047:bit0-4 nan.byte7 = 0b0 << 7 | 0b1111 << 3 | 0b111; //BIT56-63 s=x, e=2047:bit5-11 byte[] bytes = new byte[]{ nan.byte0, nan.byte1, nan.byte2, nan.byte3, nan.byte4, nan.byte5, nan.byte6, nan.byte7, }; System.Console.WriteLine($"{IsNaN(bytes)} / {nan.doubleValue}"); } static public bool IsNaN(byte[] binary) { // see also: https://docs.oracle.com/cd/E19957-01/806-4847/ncg_math.html /* 0b 0 11111111111 xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxx + -----+----- -----------------------+---------------------------------- | | | | | +----------------- f: 最低一つのビットが1 | +----------------------------------------------- e: 2047 +------------------------------------------------------ s: 符号 */ return // e == 2047 (binary[7] & 0b01111111) == 0b01111111 && (binary[6] & 0b11110000) == 0b11110000 && // f != 0 ( (binary[6] & 0b00001111) != 0 || (binary[5] & 0b11111111) != 0 || (binary[4] & 0b11111111) != 0 || (binary[3] & 0b11111111) != 0 || (binary[2] & 0b11111111) != 0 || (binary[1] & 0b11111111) != 0 || (binary[0] & 0b11111111) != 0 ); } } ~~~