Beispiel #1
0
 public void TestEndiannessReverse()
 {
     Assert.AreEqual(0xBBAA, Endianness.Reverse((ushort)0xAABB));
     Assert.AreEqual(0xDDCCBBAA, Endianness.Reverse(0xAABBCCDD));
     Assert.AreEqual(0x7766554433221100, Endianness.Reverse(0x0011223344556677));
 }
Beispiel #2
0
        protected object ReadPOD(bool optional)
        {
            var tl = new TypeLength(Source);

            if (optional && tl.IsOptionalMarker)
            {
                return(null);
            }

            switch (tl.Type)
            {
            case SMLType.Boolean:
                return(_reader.ReadByte() != 0);

            case SMLType.OctetString:
                return(_reader.ReadBytes(tl.Length));

            case SMLType.Integer:
            {
                var raw = FillPow2(tl);
                if (raw.Length == 1)
                {
                    return((sbyte)raw[0]);
                }
                if (raw.Length == 2)
                {
                    return(Endianness.Reverse(BitConverter.ToInt16(raw, 0)));
                }
                if (raw.Length == 4)
                {
                    return(Endianness.Reverse(BitConverter.ToInt32(raw, 0)));
                }
                if (raw.Length == 8)
                {
                    return(Endianness.Reverse(BitConverter.ToInt64(raw, 0)));
                }
                throw new InvalidDataException("Invalid integer, expected 1, 2, 4 or 8 bytes, got " + raw.Length);
            }

            case SMLType.Unsigned:
            {
                var raw = FillPow2(tl);
                if (raw.Length == 1)
                {
                    return(raw[0]);
                }
                if (raw.Length == 2)
                {
                    return(Endianness.Reverse(BitConverter.ToUInt16(raw, 0)));
                }
                if (raw.Length == 4)
                {
                    return(Endianness.Reverse(BitConverter.ToUInt32(raw, 0)));
                }
                if (raw.Length == 8)
                {
                    return(Endianness.Reverse(BitConverter.ToUInt64(raw, 0)));
                }
                throw new InvalidDataException("Invalid unsigned, expected 1, 2, 4 or 8 bytes, got " + raw.Length);
            }

            case SMLType.List:
                // we don't handle this directly, as in recursive
                // we could, but it doesn't fit into the reflection/type model
                throw new InvalidDataException("ReadPOD is only for POD types");
            }

            throw new InvalidDataException("Invalid TypeLength");
        }