Esempio n. 1
0
        /// <summary>
        /// Read a DXF record from a binary DXF file
        /// </summary>
        /// <param name="rec"></param>
        /// <param name="lineNumber"></param>
        /// <param name="readingTextEntity"></param>
        /// <returns></returns>
        public bool ReadBinaryDXFRecord(out DXFRecord rec,
                                        ref int lineNumber,
                                        bool readingTextEntity = false)
        {
            rec = new DXFRecord();
            var buffer = new byte[100];

            // Read the record number
            if (_dXFFileIsPostR13c3)
            {
                _binarydxfFile.Read(buffer, 0, 2);
                rec.recType = BitConverter.ToUInt16(buffer);
            }
            else
            {
                var binaryRecType1 = _binarydxfFile.ReadByte();

                if (binaryRecType1 != 255)
                {
                    rec.recType = (ushort)binaryRecType1;
                }
                else // escaped record number
                {
                    _binarydxfFile.Read(buffer, 0, 2);
                    rec.recType = BitConverter.ToUInt16(buffer);
                }
            }

            if (rec.recType >= BinaryDXFRecordTypeLookUp.Length)
            {
                return(false);
            }

            switch (BinaryDXFRecordTypeLookUp[rec.recType])
            {
            case BinaryDXFRecordType_String:
                var builder = new StringBuilder();
                // read chars until we find a #0

                byte theByte;
                do
                {
                    theByte = (byte)_binarydxfFile.ReadByte();
                    if (theByte != 0)
                    {
                        builder.Append((char)theByte);
                    }
                } while  (theByte != 0);

                rec.s = builder.ToString();

                // We do not want to remove leading or trailing spaces from
                // the text in DXF text entities (TEXT and MTEXT). These
                // group codes 1 (for TEXT) and 1&3 (for MTEXT). If the caller
                // has advised it is reading a DXF text entity we no do not
                // strip the spaces from the string value.
                if (readingTextEntity)
                {
                    if (!(rec.recType == 1 || rec.recType == 3))
                    {
                        rec.s = rec.s.Trim();
                    }
                }
                else
                {
                    rec.s = rec.s.Trim();
                }
                break;

            case BinaryDXFRecordType_Real:
                _binarydxfFile.Read(buffer, 0, 8);
                rec.r = BitConverter.ToDouble(buffer);
                break;

            case BinaryDXFRecordType_Integer1:
                _binarydxfFile.Read(buffer, 0, 1);
                rec.i = buffer[0];
                break;

            case BinaryDXFRecordType_Integer2:
                _binarydxfFile.Read(buffer, 0, 2);
                rec.i = BitConverter.ToInt16(buffer);
                break;

            case BinaryDXFRecordType_Integer4:
                _binarydxfFile.Read(buffer, 0, 4);
                rec.i = BitConverter.ToInt32(buffer);
                break;

            case BinaryDXFRecordType_Integer8:
                _binarydxfFile.Read(buffer, 0, 4);
                rec.i = BitConverter.ToUInt32(buffer);
                break;

            case BinaryDXFRecordType_ExtendedData:
                rec.s = "";
                var recLength = _binarydxfFile.ReadByte();
                _binarydxfFile.Position += recLength;
                break;

            default:
                return(false);
            }

            lineNumber++;
            return(true);
        }
Esempio n. 2
0
 public Double GetDouble(int iOffset)
 {
     return(BitConverter.ToDouble(this.Buffer, iOffset));
 }
Esempio n. 3
0
 public static double GetDouble(byte[] bytes, int offset, int count) => BitConverter.ToDouble(GetByteArray(bytes, offset, count), 0);
Esempio n. 4
0
 public static double ConvertDouble(double value)
 {
     byte[] buffer = BitConverter.GetBytes(value);
     Array.Reverse(buffer);
     return(BitConverter.ToDouble(buffer, 0));
 }
Esempio n. 5
0
 public static double ReadDouble(IntPtr ptr)
 {
     byte[] bytes = new byte[sizeof(double)];
     Marshal.Copy(ptr, bytes, 0, bytes.Length);
     return(BitConverter.ToDouble(bytes, 0));
 }
Esempio n. 6
0
 public double PeekDouble()
 {
     return(BitConverter.ToDouble(_data, _position));
 }
Esempio n. 7
0
 public double ReadDouble()
 {
     byte[] byteArray = new byte[8];
     base.Read(byteArray, 0, 8);
     return(BitConverter.ToDouble(byteArray, 0));
 }
Esempio n. 8
0
 internal Double?ReadNullableDouble()
 {
     ReadValidTypeID(TypeID.NullableDouble);
     return(ReadNullable <Double?>(() => BitConverter.ToDouble(this.Reader.ReadBytes(8), 0)));
 }
Esempio n. 9
0
 public static double Swap(double value)
 {
     byte[] b = BitConverter.GetBytes(value);
     Array.Reverse(b);
     return(BitConverter.ToDouble(b, 0));
 }
Esempio n. 10
0
 private object ReadBinaryFloat()
 {
     return(BitConverter.ToDouble(ReadBytes(8), 0));
 }
Esempio n. 11
0
 internal Double ReadDouble()
 {
     ReadValidTypeID(TypeID.Double);
     return(BitConverter.ToDouble(this.Reader.ReadBytes(8), 0));
 }
Esempio n. 12
0
 public double GetObject(byte[] buffer, int offset, int count)
 {
     return(BitConverter.ToDouble(buffer, offset));
 }
Esempio n. 13
0
        public static T ReadPacket <T>(byte[] buffer, ref int idx, int len = 0)
        {
            var result = default(T);

            try
            {
                var resultType = typeof(T);
                if (resultType == typeof(int))
                {
                    result = (T)(object)BitConverter.ToInt32(buffer, idx);
                    idx   += 4;
                }
                else if (resultType == typeof(ushort))
                {
                    result = (T)(object)BitConverter.ToInt16(buffer, idx);
                    idx   += 2;
                }
                else if (resultType == typeof(uint))
                {
                    result = (T)(object)BitConverter.ToUInt32(buffer, idx);
                    idx   += 4;
                }
                else if (resultType == typeof(byte))
                {
                    result = (T)(object)buffer[idx];
                    idx   += 1;
                }
                else if (resultType == typeof(bool))
                {
                    result = (T)(object)(buffer[idx] == 1);
                    idx   += 1;
                }
                else if (resultType == typeof(float))
                {
                    result = (T)(object)BitConverter.ToDouble(buffer, idx);
                    idx   += 8;
                }
                else if (resultType == typeof(string))
                {
                    result = (T)(object)EncodingBig5.GetString(buffer, idx, len);
                    idx   += len;
                }
                else if (resultType == typeof(byte[]))
                {
                    var tmp = new byte[len];
                    Array.Copy(buffer, idx, tmp, 0, len);
                    idx += len;
                }
                else if (resultType == typeof(double))
                {
                    result = (T)(object)BitConverter.ToDouble(buffer, idx);
                    idx   += 8;
                }
                else
                {
                    throw new Exception("[ByteUtil.ReadPacket]UNKNOWN TYPE ![TRACE]" + TraceUtil.GetTraceMethodName(5));
                }
            }
            catch (Exception ex)
            {
                throw new Exception("[ByteUtil.ReadPacket]" + ex.Message + " [TRACE] " + ex.StackTrace);
            }
            return(result);
        }
Esempio n. 14
0
            public string Evaluate()
            {
                Stack <object> stack = new Stack <object>();

                object[] reg = new object[8];

                for (int i = 0; i < Bytes.Length; i++)
                {
                    var b = Bytes[i];
                    if (b >= 0x3F && b <= 0x7F)
                    {
                        stack.Push(b - 64);
                    }
                    else if (b == 0xA5)
                    {
                        var  sb       = new StringBuilder();
                        char nextChar = '?';
                        do
                        {
                            nextChar = BitConverter.ToChar(Bytes, i + 1);
                            if (nextChar != (char)0)
                            {
                                sb.Append(nextChar);
                            }
                            i += 2;
                        }while (nextChar != (char)0);
                        stack.Push(sb.ToString());
                    }
                    else if (b == 0x80)
                    {
                        stack.Push(BitConverter.ToSingle(Bytes, i + 1));
                        i += 4;
                    }
                    else if (b == 0x81)
                    {
                        stack.Push(BitConverter.ToDouble(Bytes, i + 1));
                        i += 8;
                    }
                    else if (b == 0x82)
                    {
                        stack.Push(BitConverter.ToInt32(Bytes, i + 1));
                        i += 4;
                    }
                    else if (b == 0x84)
                    {
                        var id = Convert.ToInt32(stack.Pop());
                        stack.Push(EzCommand.GetString(id));
                    }
                    else if (b == 0x85)
                    {
                        var arg1 = stack.Pop();
                        var id   = Convert.ToInt32(stack.Pop());
                        stack.Push(EzCommand.GetString(id, arg1));
                    }
                    else if (b == 0x86)
                    {
                        var arg2 = stack.Pop();
                        var arg1 = stack.Pop();
                        var id   = Convert.ToInt32(stack.Pop());
                        stack.Push(EzCommand.GetString(id, arg1, arg2));
                    }
                    else if (b >= 0x91 && b <= 0x96)
                    {
                        var item2 = stack.Pop();
                        var item1 = stack.Pop();
                        stack.Push($"({item1}) {GetComp(b)} ({item2})");
                    }
                    else if (b == 0x98)
                    {
                        var item2 = stack.Pop();
                        var item1 = stack.Pop();
                        stack.Push($"({item1}) && ({item2})");
                    }
                    else if (b == 0x99)
                    {
                        var item2 = stack.Pop();
                        var item1 = stack.Pop();
                        stack.Push($"({item1}) || ({item2})");
                    }
                    else if (b == 0xA6)
                    {
                        stack.Push($"[CONT.]");
                    }
                    else if (b >= 0xA7 && b <= 0xAE)
                    {
                        byte regIndex = (byte)(b - 0xA7);
                        var  item     = stack.Peek();
                        stack.Push($"{item} => REG[{regIndex}]");
                        reg[regIndex] = item;
                    }
                    else if (b >= 0xAF && b <= 0xB6)
                    {
                        byte regIndex = (byte)(b - 0xAF);
                        stack.Push($"REG[{regIndex}] => {reg[regIndex]}");
                    }
                    else if (b == 0xB7)
                    {
                        stack.Push($"[STOP IF FALSE]");
                    }
                    else if (b == 0xA1)
                    {
                        //stack.Push("\n");
                    }
                    else if (b >= 0x8C && b <= 0x8F)
                    {
                        var item2 = stack.Pop();
                        var item1 = stack.Pop();
                        stack.Push($"({item1}) <op 0x{b:X2}> ({item2})");
                    }
                    else
                    {
                        stack.Push($"<?0x{b:X2}?>");
                    }
                }
                return(string.Join(", ", stack));
            }
Esempio n. 15
0
 public double ReadDouble()
 {
     byte[] temp = BitConverter.GetBytes(reader.ReadDouble());
     Array.Reverse(temp);
     return(BitConverter.ToDouble(temp, 0));
 }
Esempio n. 16
0
 private static Double swapByteOrder(Double value)
 {
     Byte[] buffer = BitConverter.GetBytes(value);
     Array.Reverse(buffer, 0, buffer.Length);
     return(BitConverter.ToDouble(buffer, 0));
 }
Esempio n. 17
0
 public void WriteDouble(double v)
 {
     byte[] temp = BitConverter.GetBytes(v);
     Array.Reverse(temp);
     writer.Write(BitConverter.ToDouble(temp, 0));
 }
Esempio n. 18
0
        /// <summary>
        /// Gets the value(s) of a tag in an open TIFF file.
        /// </summary>
        /// <param name="tif">An instance of the <see cref="Tiff"/> class.</param>
        /// <param name="tag">The tag.</param>
        /// <returns>The value(s) of a tag in an open TIFF file/stream as array of
        /// <see cref="FieldValue"/> objects or <c>null</c> if there is no such tag set.</returns>
        /// <seealso cref="Tiff.GetField"/>
        public virtual FieldValue[] GetField(Tiff tif, TiffTag tag)
        {
            TiffDirectory td = tif.m_dir;

            FieldValue[] result = null;

            switch (tag)
            {
            case TiffTag.SUBFILETYPE:
                result = new FieldValue[1];
                result[0].Set(td.td_subfiletype);
                break;

            case TiffTag.IMAGEWIDTH:
                result = new FieldValue[1];
                result[0].Set(td.td_imagewidth);
                break;

            case TiffTag.IMAGELENGTH:
                result = new FieldValue[1];
                result[0].Set(td.td_imagelength);
                break;

            case TiffTag.BITSPERSAMPLE:
                result = new FieldValue[1];
                result[0].Set(td.td_bitspersample);
                break;

            case TiffTag.COMPRESSION:
                result = new FieldValue[1];
                result[0].Set(td.td_compression);
                break;

            case TiffTag.PHOTOMETRIC:
                result = new FieldValue[1];
                result[0].Set(td.td_photometric);
                break;

            case TiffTag.THRESHHOLDING:
                result = new FieldValue[1];
                result[0].Set(td.td_threshholding);
                break;

            case TiffTag.FILLORDER:
                result = new FieldValue[1];
                result[0].Set(td.td_fillorder);
                break;

            case TiffTag.ORIENTATION:
                result = new FieldValue[1];
                result[0].Set(td.td_orientation);
                break;

            case TiffTag.SAMPLESPERPIXEL:
                result = new FieldValue[1];
                result[0].Set(td.td_samplesperpixel);
                break;

            case TiffTag.ROWSPERSTRIP:
                result = new FieldValue[1];
                result[0].Set(td.td_rowsperstrip);
                break;

            case TiffTag.MINSAMPLEVALUE:
                result = new FieldValue[1];
                result[0].Set(td.td_minsamplevalue);
                break;

            case TiffTag.MAXSAMPLEVALUE:
                result = new FieldValue[1];
                result[0].Set(td.td_maxsamplevalue);
                break;

            case TiffTag.SMINSAMPLEVALUE:
                result = new FieldValue[1];
                result[0].Set(td.td_sminsamplevalue);
                break;

            case TiffTag.SMAXSAMPLEVALUE:
                result = new FieldValue[1];
                result[0].Set(td.td_smaxsamplevalue);
                break;

            case TiffTag.XRESOLUTION:
                result = new FieldValue[1];
                result[0].Set(td.td_xresolution);
                break;

            case TiffTag.YRESOLUTION:
                result = new FieldValue[1];
                result[0].Set(td.td_yresolution);
                break;

            case TiffTag.PLANARCONFIG:
                result = new FieldValue[1];
                result[0].Set(td.td_planarconfig);
                break;

            case TiffTag.XPOSITION:
                result = new FieldValue[1];
                result[0].Set(td.td_xposition);
                break;

            case TiffTag.YPOSITION:
                result = new FieldValue[1];
                result[0].Set(td.td_yposition);
                break;

            case TiffTag.RESOLUTIONUNIT:
                result = new FieldValue[1];
                result[0].Set(td.td_resolutionunit);
                break;

            case TiffTag.PAGENUMBER:
                result = new FieldValue[2];
                result[0].Set(td.td_pagenumber[0]);
                result[1].Set(td.td_pagenumber[1]);
                break;

            case TiffTag.HALFTONEHINTS:
                result = new FieldValue[2];
                result[0].Set(td.td_halftonehints[0]);
                result[1].Set(td.td_halftonehints[1]);
                break;

            case TiffTag.COLORMAP:
                result = new FieldValue[3];
                result[0].Set(td.td_colormap[0]);
                result[1].Set(td.td_colormap[1]);
                result[2].Set(td.td_colormap[2]);
                break;

            case TiffTag.STRIPOFFSETS:
            case TiffTag.TILEOFFSETS:
                result = new FieldValue[1];
                result[0].Set(td.td_stripoffset);
                break;

            case TiffTag.STRIPBYTECOUNTS:
            case TiffTag.TILEBYTECOUNTS:
                result = new FieldValue[1];
                result[0].Set(td.td_stripbytecount);
                break;

            case TiffTag.MATTEING:
                result = new FieldValue[1];
                result[0].Set((td.td_extrasamples == 1 && td.td_sampleinfo[0] == ExtraSample.ASSOCALPHA));
                break;

            case TiffTag.EXTRASAMPLES:
                result = new FieldValue[2];
                result[0].Set(td.td_extrasamples);
                result[1].Set(td.td_sampleinfo);
                break;

            case TiffTag.TILEWIDTH:
                result = new FieldValue[1];
                result[0].Set(td.td_tilewidth);
                break;

            case TiffTag.TILELENGTH:
                result = new FieldValue[1];
                result[0].Set(td.td_tilelength);
                break;

            case TiffTag.TILEDEPTH:
                result = new FieldValue[1];
                result[0].Set(td.td_tiledepth);
                break;

            case TiffTag.DATATYPE:
                switch (td.td_sampleformat)
                {
                case SampleFormat.UINT:
                    result = new FieldValue[1];
                    result[0].Set(DATATYPE_UINT);
                    break;

                case SampleFormat.INT:
                    result = new FieldValue[1];
                    result[0].Set(DATATYPE_INT);
                    break;

                case SampleFormat.IEEEFP:
                    result = new FieldValue[1];
                    result[0].Set(DATATYPE_IEEEFP);
                    break;

                case SampleFormat.VOID:
                    result = new FieldValue[1];
                    result[0].Set(DATATYPE_VOID);
                    break;
                }
                break;

            case TiffTag.SAMPLEFORMAT:
                result = new FieldValue[1];
                result[0].Set(td.td_sampleformat);
                break;

            case TiffTag.IMAGEDEPTH:
                result = new FieldValue[1];
                result[0].Set(td.td_imagedepth);
                break;

            case TiffTag.SUBIFD:
                result = new FieldValue[2];
                result[0].Set(td.td_nsubifd);
                result[1].Set(td.td_subifd);
                break;

            case TiffTag.YCBCRPOSITIONING:
                result = new FieldValue[1];
                result[0].Set(td.td_ycbcrpositioning);
                break;

            case TiffTag.YCBCRSUBSAMPLING:
                result = new FieldValue[2];
                result[0].Set(td.td_ycbcrsubsampling[0]);
                result[1].Set(td.td_ycbcrsubsampling[1]);
                break;

            case TiffTag.TRANSFERFUNCTION:
                result = new FieldValue[3];
                result[0].Set(td.td_transferfunction[0]);
                if (td.td_samplesperpixel - td.td_extrasamples > 1)
                {
                    result[1].Set(td.td_transferfunction[1]);
                    result[2].Set(td.td_transferfunction[2]);
                }
                break;

            case TiffTag.REFERENCEBLACKWHITE:
                if (td.td_refblackwhite != null)
                {
                    result = new FieldValue[1];
                    result[0].Set(td.td_refblackwhite);
                }
                break;

            case TiffTag.INKNAMES:
                result = new FieldValue[1];
                result[0].Set(td.td_inknames);
                break;

            default:
                // This can happen if multiple images are open with
                // different codecs which have private tags. The global tag
                // information table may then have tags that are valid for
                // one file but not the other. If the client tries to get a
                // tag that is not valid for the image's codec then we'll
                // arrive here.
                TiffFieldInfo fip = tif.FindFieldInfo(tag, TiffType.ANY);
                if (fip == null || fip.Bit != FieldBit.Custom)
                {
                    Tiff.ErrorExt(tif, tif.m_clientdata, "_TIFFVGetField",
                                  "{0}: Invalid {1}tag \"{2}\" (not supported by codec)",
                                  tif.m_name, Tiff.isPseudoTag(tag) ? "pseudo-" : string.Empty,
                                  fip != null ? fip.Name : "Unknown");
                    result = null;
                    break;
                }

                // Do we have a custom value?
                result = null;
                for (int i = 0; i < td.td_customValueCount; i++)
                {
                    TiffTagValue tv = td.td_customValues[i];
                    if (tv.info.Tag != tag)
                    {
                        continue;
                    }

                    if (fip.PassCount)
                    {
                        result = new FieldValue[2];

                        if (fip.ReadCount == TiffFieldInfo.Variable2)
                        {
                            result[0].Set(tv.count);
                        }
                        else
                        {
                            // Assume TiffFieldInfo.Variable
                            result[0].Set(tv.count);
                        }

                        result[1].Set(tv.value);
                    }
                    else
                    {
                        if ((fip.Type == TiffType.ASCII ||
                             fip.ReadCount == TiffFieldInfo.Variable ||
                             fip.ReadCount == TiffFieldInfo.Variable2 ||
                             fip.ReadCount == TiffFieldInfo.Spp ||
                             tv.count > 1) && fip.Tag != TiffTag.PAGENUMBER &&
                            fip.Tag != TiffTag.HALFTONEHINTS &&
                            fip.Tag != TiffTag.YCBCRSUBSAMPLING &&
                            fip.Tag != TiffTag.DOTRANGE)
                        {
                            result = new FieldValue[1];
                            byte[] value = tv.value;

                            if (fip.Type == TiffType.ASCII &&
                                tv.value.Length > 0 &&
                                tv.value[tv.value.Length - 1] == 0)
                            {
                                // cut unwanted zero at the end
                                value = new byte[Math.Max(tv.value.Length - 1, 0)];
                                Buffer.BlockCopy(tv.value, 0, value, 0, value.Length);
                            }

                            result[0].Set(value);
                        }
                        else
                        {
                            result = new FieldValue[tv.count];
                            byte[] val    = tv.value;
                            int    valPos = 0;
                            for (int j = 0; j < tv.count; j++, valPos += Tiff.dataSize(tv.info.Type))
                            {
                                switch (fip.Type)
                                {
                                case TiffType.BYTE:
                                case TiffType.UNDEFINED:
                                case TiffType.SBYTE:
                                    result[j].Set(val[valPos]);
                                    break;

                                case TiffType.SHORT:
                                case TiffType.SSHORT:
                                    result[j].Set(BitConverter.ToInt16(val, valPos));
                                    break;

                                case TiffType.LONG:
                                case TiffType.IFD:
                                case TiffType.SLONG:
                                    result[j].Set(BitConverter.ToInt32(val, valPos));
                                    break;

                                case TiffType.RATIONAL:
                                case TiffType.SRATIONAL:
                                case TiffType.FLOAT:
                                    result[j].Set(BitConverter.ToSingle(val, valPos));
                                    break;

                                case TiffType.DOUBLE:
                                    result[j].Set(BitConverter.ToDouble(val, valPos));
                                    break;

                                default:
                                    result = null;
                                    break;
                                }
                            }
                        }
                    }
                    break;
                }
                break;
            }

            return(result);
        }
Esempio n. 19
0
 public static double Reverse(double value)
 {
     byte[] bytes = BitConverter.GetBytes(value);
     Array.Reverse(bytes);
     return(BitConverter.ToDouble(bytes, 0));
 }
Esempio n. 20
0
 public double ReadDouble(IntPtr address)
 {
     return(BitConverter.ToDouble(ReadBytes(address, 8), 0));
 }
Esempio n. 21
0
        public static double ToDouble(byte[] value, int startIndex, bool convert)
        {
            double result = BitConverter.ToDouble(value, startIndex);

            return(convert ? ConvertDouble(result) : result);
        }
Esempio n. 22
0
        /// <summary>
        /// This will get the value for a basic data type in this data
        /// </summary>
        /// <param name="type">The type to convert the bytes for</typeparam>
        /// <param name="start">The byte start index to read from</param>
        /// <returns>The value of the object</returns>
        public object GetBasicType(Type type, int start, bool moveIndex = false)
        {
            if (type == typeof(sbyte))
            {
                if (moveIndex)
                {
                    MoveStartIndex(sizeof(sbyte));
                }

                return((sbyte)byteArr[start]);
            }
            else if (type == typeof(byte))
            {
                if (moveIndex)
                {
                    MoveStartIndex(sizeof(byte));
                }

                return(byteArr[start]);
            }
            else if (type == typeof(char))
            {
                if (moveIndex)
                {
                    MoveStartIndex(sizeof(char));
                }

                return(byteArr[start]);
            }
            else if (type == typeof(short))
            {
                if (moveIndex)
                {
                    MoveStartIndex(sizeof(short));
                }

                return(BitConverter.ToInt16(byteArr, start));
            }
            else if (type == typeof(ushort))
            {
                if (moveIndex)
                {
                    MoveStartIndex(sizeof(ushort));
                }

                return(BitConverter.ToUInt16(byteArr, start));
            }
            else if (type == typeof(bool))
            {
                if (moveIndex)
                {
                    MoveStartIndex(sizeof(bool));
                }

                return(BitConverter.ToBoolean(byteArr, start));
            }
            else if (type == typeof(int))
            {
                if (moveIndex)
                {
                    MoveStartIndex(sizeof(int));
                }

                return(BitConverter.ToInt32(byteArr, start));
            }
            else if (type == typeof(uint))
            {
                if (moveIndex)
                {
                    MoveStartIndex(sizeof(uint));
                }

                return(BitConverter.ToUInt32(byteArr, start));
            }
            else if (type == typeof(float))
            {
                if (moveIndex)
                {
                    MoveStartIndex(sizeof(float));
                }

                return(BitConverter.ToSingle(byteArr, start));
            }
            else if (type == typeof(long))
            {
                if (moveIndex)
                {
                    MoveStartIndex(sizeof(long));
                }

                return(BitConverter.ToInt64(byteArr, start));
            }
            else if (type == typeof(ulong))
            {
                if (moveIndex)
                {
                    MoveStartIndex(sizeof(ulong));
                }

                return(BitConverter.ToUInt64(byteArr, start));
            }
            else if (type == typeof(double))
            {
                if (moveIndex)
                {
                    MoveStartIndex(sizeof(double));
                }

                return(BitConverter.ToDouble(byteArr, start));
            }
            else if (type == typeof(string))
            {
                return(GetString(start, moveIndex));
            }
            else if (type == typeof(Vector3D))
            {
                return(GetVector(start, moveIndex));
            }
            else if (type.IsArray)
            {
                int  rank       = type.GetArrayRank();
                Type targetType = type.GetElementType();

                //int startingIndex = StartIndex();
                MoveStartIndex(sizeof(int));

                if (rank > 4)
                {
                    throw new Exception("Currently the system only supports up to 4 dimensions in an array");
                }

                int i, j, k, l, x, y, z, w;
                switch (rank)
                {
                case 1:
                    x = GetBasicType <int>(StartIndex(), true);
                    object[] one = new object[x];
                    for (i = 0; i < x; i++)
                    {
                        one[i] = GetBasicType(targetType, StartIndex(), true);
                    }
                    return(one);

                case 2:
                    x             = GetBasicType <int>(StartIndex(), true);
                    y             = GetBasicType <int>(StartIndex(), true);
                    object[,] two = new object[x, y];
                    for (i = 0; i < x; i++)
                    {
                        for (j = 0; j < y; j++)
                        {
                            two[i, j] = GetBasicType(targetType, StartIndex(), true);
                        }
                    }
                    return(two);

                case 3:
                    x = GetBasicType <int>(StartIndex(), true);
                    y = GetBasicType <int>(StartIndex(), true);
                    z = GetBasicType <int>(StartIndex(), true);
                    object[,,] three = new object[x, y, z];
                    for (i = 0; i < x; i++)
                    {
                        for (j = 0; j < y; j++)
                        {
                            for (k = 0; k < z; k++)
                            {
                                three[i, j, k] = GetBasicType(targetType, StartIndex(), true);
                            }
                        }
                    }
                    return(three);

                case 4:
                    x = GetBasicType <int>(StartIndex(), true);
                    y = GetBasicType <int>(StartIndex(), true);
                    z = GetBasicType <int>(StartIndex(), true);
                    w = GetBasicType <int>(StartIndex(), true);
                    object[,,,] four = new object[x, y, z, w];
                    for (i = 0; i < x; i++)
                    {
                        for (j = 0; j < y; j++)
                        {
                            for (k = 0; k < z; k++)
                            {
                                for (l = 0; l < w; l++)
                                {
                                    four[i, j, k, l] = GetBasicType(targetType, StartIndex(), true);
                                }
                            }
                        }
                    }
                    return(four);
                }

                throw new Exception("Deserialize case not found for this array");
            }
            else if (type.IsEnum)
            {
                return(GetBasicType(Enum.GetUnderlyingType(type), start, moveIndex));
            }
            else
            {
                throw new Exception("The type " + type.ToString() + " isn't getable from basic type, maybe try one of the other getters?");
            }
        }
Esempio n. 23
0
        /// <summary>
        /// Deserialize a stream of bytes into a message.<br />Use with caution.
        /// </summary>
        public static Message Deserialize(MemoryStream memoryStream)
        {
            // if `leaveOpen` is left false, this will dispose the memory stream once the BitEncodedStreamReader is disposed.
            // we don't want to dispose the memory stream because we continually reuse it for reading
            var rawBufferData = memoryStream.GetBufferWithReflection().Span;
            var stream        = new BitEncodedSpanReader(rawBufferData);
            var scope         = (ConnectionScope)stream.ReadByte();
            var type          = (MessageType)stream.Read7BitEncodedInt();

            // i have chosen to initialize the list to this mathemetical number,
            // because i don't want it to go from 4 -> 16 -> 64 ...
            // and would rather have it start at like 123 if the length is 32 * 123
            var argData = new List <object>(rawBufferData.Length / 32);

            while (stream.Position < rawBufferData.Length)
            {
                var patternType = stream.ReadByte();

                // it is very common for there to be empty blocks in a world
                // this is a minor optimization which will try to excersize that
                while (patternType == _patternBooleanFalse)
                {
                    argData.Add(false);

                    if (stream.Position >= rawBufferData.Length)
                    {
                        goto EndOfFunction;
                    }
                    patternType = stream.ReadByte();
                }

                switch (patternType)
                {
                // we can guarantee that this is not possible, because
                // we ruled it out with the optimization above
                // case _patternBooleanFalse: argData.Add(false); break;
                case _patternIntPos: argData.Add(stream.Read7BitEncodedInt()); break;

                case _patternString: argData.Add(stream.ReadString()); break;

                case _patternIntNeg: argData.Add(-stream.Read7BitEncodedInt() - 1); break;

                case _patternBooleanTrue: argData.Add(true); break;

                case _patternDouble: argData.Add(BitConverter.ToDouble(stream.ReadBytes(8))); break;

                case _patternBytes:
                {
                    var length = stream.Read7BitEncodedInt();
                    argData.Add(stream.ReadBytes(length).ToArray());
                }
                break;

                case _patternObject:
                {
                    var objectArgs = new MessageObject();
                    while (stream.ReadByte() != _patternObjectEnd)
                    {
                        stream.Position--;

                        object value;
                        switch (stream.ReadByte())
                        {
                        case _patternString: value = stream.ReadString(); break;

                        case _patternIntPos: value = stream.Read7BitEncodedInt(); break;

                        case _patternIntNeg: value = -stream.Read7BitEncodedInt() - 1; break;

                        case _patternDouble: value = BitConverter.ToDouble(stream.ReadBytes(8)); break;

                        case _patternBooleanFalse: value = false; break;

                        case _patternBooleanTrue: value = true; break;

                        case _patternBytes:
                        {
                            var length = stream.Read7BitEncodedInt();
                            value = stream.ReadBytes(length).ToArray();
                        }
                        break;

                        default: throw new InvalidDataException($"Invalid pattern type {patternType} in MessageObject.");
                        }

                        objectArgs.Add(stream.ReadString(), value);
                    }

                    argData.Add(objectArgs);
                }
                break;

                default: throw new InvalidDataException($"Invalid pattern type {patternType}.");
                }
            }

EndOfFunction:
            return(new Message(scope, type, argData.ToArray()));
        }
Esempio n. 24
0
 public double PeakDouble()
 {
     return(BitConverter.ToDouble(bytes, index));
 }
 public double DecryptToDouble(string cipherText)
 {
     return(BitConverter.ToDouble(this.Decrypt(Convert.FromBase64String(cipherText)), 0));
 }
        private object[] ProcessMessageObjects(byte[] message, string name, string format)
        {
            char[] form = format.ToCharArray();

            int offset = 0;

            List <object> answer = new List <object>();

            foreach (char ch in form)
            {
                switch (ch)
                {
                case 'b':
                    answer.Add((sbyte)message[offset]);
                    offset++;
                    break;

                case 'B':
                    answer.Add(message[offset]);
                    offset++;
                    break;

                case 'h':
                    answer.Add(BitConverter.ToInt16(message, offset));
                    offset += 2;
                    break;

                case 'H':
                    answer.Add(BitConverter.ToUInt16(message, offset));
                    offset += 2;
                    break;

                case 'i':
                    answer.Add(BitConverter.ToInt32(message, offset));
                    offset += 4;
                    break;

                case 'I':
                    answer.Add(BitConverter.ToUInt32(message, offset));
                    offset += 4;
                    break;

                case 'q':
                    answer.Add(BitConverter.ToInt64(message, offset));
                    offset += 8;
                    break;

                case 'Q':
                    answer.Add(BitConverter.ToUInt64(message, offset));
                    offset += 8;
                    break;

                case 'f':
                    answer.Add(BitConverter.ToSingle(message, offset));
                    offset += 4;
                    break;

                case 'd':
                    answer.Add(BitConverter.ToDouble(message, offset));
                    offset += 8;
                    break;

                case 'c':
                    answer.Add((BitConverter.ToInt16(message, offset) / 100.0));
                    offset += 2;
                    break;

                case 'C':
                    answer.Add((BitConverter.ToUInt16(message, offset) / 100.0));
                    offset += 2;
                    break;

                case 'e':
                    answer.Add((BitConverter.ToInt32(message, offset) / 100.0));
                    offset += 4;
                    break;

                case 'E':
                    answer.Add((BitConverter.ToUInt32(message, offset) / 100.0));
                    offset += 4;
                    break;

                case 'L':
                    answer.Add(((double)BitConverter.ToInt32(message, offset) / 10000000.0));
                    offset += 4;
                    break;

                case 'n':
                    answer.Add(ASCIIEncoding.ASCII.GetString(message, offset, 4).Trim(new char[] { '\0' }));
                    offset += 4;
                    break;

                case 'N':
                    answer.Add(ASCIIEncoding.ASCII.GetString(message, offset, 16).Trim(new char[] { '\0' }));
                    offset += 16;
                    break;

                case 'M':
                    int modeno = message[offset];
                    answer.Add(modeno);
                    offset++;
                    break;

                case 'Z':
                    answer.Add(ASCIIEncoding.ASCII.GetString(message, offset, 64).Trim(new char[] { '\0' }));
                    offset += 64;
                    break;

                default:
                    return(null);
                }
            }
            return(answer.ToArray());
        }
Esempio n. 27
0
        /// <summary>
        /// Reads an 8-byte floating point value from the current stream and advances the current position of the stream by eight bytes.
        /// </summary>
        /// <returns>A</returns>
        public override double ReadDouble()
        {
            var buffer = ReadByteArrayEndian(8);

            return(BitConverter.ToDouble(buffer, 0));
        }
        /*
         * 105    +Format characters in the format string for binary log messages
         * 106    +  b   : int8_t
         * 107    +  B   : uint8_t
         * 108    +  h   : int16_t
         * 109    +  H   : uint16_t
         * 110    +  i   : int32_t
         * 111    +  I   : uint32_t
         * 112    +  f   : float
         *     d   : double
         * 113    +  N   : char[16]
         * 114    +  c   : int16_t * 100
         * 115    +  C   : uint16_t * 100
         * 116    +  e   : int32_t * 100
         * 117    +  E   : uint32_t * 100
         * 118    +  L   : uint32_t latitude/longitude
         * 119    + */


        /// <summary>
        /// Convert to ascii based on the existing format message
        /// </summary>
        /// <param name="message">raw binary message</param>
        /// <param name="name">Message type name</param>
        /// <param name="format">format string containing packet structure</param>
        /// <returns>formated ascii string</returns>
        string ProcessMessage(byte[] message, string name, string format)
        {
            char[] form = format.ToCharArray();

            int offset = 0;

            StringBuilder line = new StringBuilder(name, 1024);

            foreach (char ch in form)
            {
                switch (ch)
                {
                case 'b':
                    line.Append(", " + (sbyte)message[offset]);
                    offset++;
                    break;

                case 'B':
                    line.Append(", " + message[offset]);
                    offset++;
                    break;

                case 'h':
                    line.Append(", " +
                                BitConverter.ToInt16(message, offset)
                                .ToString(System.Globalization.CultureInfo.InvariantCulture));
                    offset += 2;
                    break;

                case 'H':
                    line.Append(", " +
                                BitConverter.ToUInt16(message, offset)
                                .ToString(System.Globalization.CultureInfo.InvariantCulture));
                    offset += 2;
                    break;

                case 'i':
                    line.Append(", " +
                                BitConverter.ToInt32(message, offset)
                                .ToString(System.Globalization.CultureInfo.InvariantCulture));
                    offset += 4;
                    break;

                case 'I':
                    line.Append(", " +
                                BitConverter.ToUInt32(message, offset)
                                .ToString(System.Globalization.CultureInfo.InvariantCulture));
                    offset += 4;
                    break;

                case 'q':
                    line.Append(", " +
                                BitConverter.ToInt64(message, offset)
                                .ToString(System.Globalization.CultureInfo.InvariantCulture));
                    offset += 8;
                    break;

                case 'Q':
                    line.Append(", " +
                                BitConverter.ToUInt64(message, offset)
                                .ToString(System.Globalization.CultureInfo.InvariantCulture));
                    offset += 8;
                    break;

                case 'f':
                    line.Append(", " +
                                BitConverter.ToSingle(message, offset)
                                .ToString(System.Globalization.CultureInfo.InvariantCulture));
                    offset += 4;
                    break;

                case 'd':
                    line.Append(", " +
                                BitConverter.ToDouble(message, offset)
                                .ToString(System.Globalization.CultureInfo.InvariantCulture));
                    offset += 8;
                    break;

                case 'c':
                    line.Append(", " +
                                (BitConverter.ToInt16(message, offset) / 100.0).ToString("0.00",
                                                                                         System.Globalization.CultureInfo.InvariantCulture));
                    offset += 2;
                    break;

                case 'C':
                    line.Append(", " +
                                (BitConverter.ToUInt16(message, offset) / 100.0).ToString("0.00",
                                                                                          System.Globalization.CultureInfo.InvariantCulture));
                    offset += 2;
                    break;

                case 'e':
                    line.Append(", " +
                                (BitConverter.ToInt32(message, offset) / 100.0).ToString("0.00",
                                                                                         System.Globalization.CultureInfo.InvariantCulture));
                    offset += 4;
                    break;

                case 'E':
                    line.Append(", " +
                                (BitConverter.ToUInt32(message, offset) / 100.0).ToString("0.00",
                                                                                          System.Globalization.CultureInfo.InvariantCulture));
                    offset += 4;
                    break;

                case 'L':
                    line.Append(", " +
                                ((double)BitConverter.ToInt32(message, offset) / 10000000.0).ToString(
                                    System.Globalization.CultureInfo.InvariantCulture));
                    offset += 4;
                    break;

                case 'n':
                    line.Append(", " + ASCIIEncoding.ASCII.GetString(message, offset, 4).Trim(new char[] { '\0' }));
                    offset += 4;
                    break;

                case 'N':
                    line.Append(", " + ASCIIEncoding.ASCII.GetString(message, offset, 16).Trim(new char[] { '\0' }));
                    offset += 16;
                    break;

                case 'M':
                    int    modeno      = message[offset];
                    var    modes       = Common.getModesList(MainV2.comPort.MAV.cs);
                    string currentmode = "";

                    foreach (var mode in modes)
                    {
                        if (mode.Key == modeno)
                        {
                            currentmode = mode.Value;
                            break;
                        }
                    }

                    line.Append(", " + currentmode);
                    offset++;
                    break;

                case 'Z':
                    line.Append(", " + ASCIIEncoding.ASCII.GetString(message, offset, 64).Trim(new char[] { '\0' }));
                    offset += 64;
                    break;

                default:
                    return("Bad Conversion");
                }
            }

            line.Append("\r\n");
            return(line.ToString());
        }
Esempio n. 29
0
 public double ReadDouble(int offset)
 {
     return(BitConverter.ToDouble(Bytes, RecordContentOffset + offset));
 }
Esempio n. 30
0
 public override DataItem GetValue(byte[] input, int index, ref int formattedDataLength)
 {
     formattedDataLength = sizeof(double);
     return(new DataItem(_name, BitConverter.ToDouble(input, index)));
 }