//private const int TOKEN_PREFIX_SMALL_INT = 0xC0; //private const int TOKEN_BYTE_INT_32 = 0x24; //private const int TOKEN_BYTE_INT_64 = 0x25; public void WriteInteger(int value) { int i = value; // First things first: let's zigzag encode number i = SmileUtil.zigzagEncode(i); // tiny (single byte) or small (type + 6-bit value) number? if (i <= 0x3F && i >= 0) { if (i <= 0x1F) // tiny { this._writer.Write((byte)((byte)VALUE_CONSTANTS.SmallInteger_BEGIN + i)); return; } // nope, just small, 2 bytes (type, 1-byte zigzag value) for 6 bit value this._Write(VALUE_CONSTANTS.Integer, (byte)(0x80 + i)); return; } // Ok: let's find minimal representation then byte b0 = (byte)(0x80 + (i & 0x3F)); //i >>>= 6; i = (int)((uint)i >> 6); if (i <= 0x7F) // 13 bits is enough (== 3 byte total encoding) { this._Write(VALUE_CONSTANTS.Integer, (byte)i, b0); return; } byte b1 = (byte)(i & 0x7F); i >>= 7; if (i <= 0x7F) { this._Write(VALUE_CONSTANTS.Integer, (byte)i, b1, b0); return; } byte b2 = (byte)(i & 0x7F); i >>= 7; if (i <= 0x7F) { this._Write(VALUE_CONSTANTS.Integer, (byte)i, b2, b1, b0); return; } // no, need all 5 bytes byte b3 = (byte)(i & 0x7F); this._Write(VALUE_CONSTANTS.Integer, (byte)(i >> 7), b3, b2, b1, b0); // throw new NotImplementedException(); }
public void WriteLong(long value) { if (value >= int.MinValue && value <= int.MaxValue) { this.WriteInteger((int)value); return; } value = SmileUtil.zigzagEncode(value); // Ok, well, we do know that 5 lowest-significant bytes are needed int i = (int)value; // 4 can be extracted from lower int byte b0 = (byte)(0x80 + (i & 0x3F)); // sign bit set in the last byte byte b1 = (byte)((i >> 6) & 0x7F); byte b2 = (byte)((i >> 13) & 0x7F); byte b3 = (byte)((i >> 20) & 0x7F); // fifth one is split between ints: value = (long)((ulong)value >> 27); byte b4 = (byte)(((int)value) & 0x7F); i = (int)(value >> 7); if (i == 0) { this._Write(VALUE_CONSTANTS.Long, b4, b3, b2, b1, b0); return; } if (i <= 0x7F) { this._Write(VALUE_CONSTANTS.Long, (byte)i, b4, b3, b2, b1, b0); return; } byte b5 = (byte)(i & 0x7F); i >>= 7; if (i <= 0x7F) { this._Write(VALUE_CONSTANTS.Long, (byte)i, b5, b4, b3, b2, b1, b0); return; } byte b6 = (byte)(i & 0x7F); i >>= 7; if (i <= 0x7F) { this._Write(VALUE_CONSTANTS.Long, (byte)i, b6, b5, b4, b3, b2, b1, b0); return; } byte b7 = (byte)(i & 0x7F); i >>= 7; if (i <= 0x7F) { this._Write(VALUE_CONSTANTS.Long, (byte)i, b7, b6, b5, b4, b3, b2, b1, b0); return; } byte b8 = (byte)(i & 0x7F); i >>= 7; // must be done, with 10 bytes! (9 * 7 + 6 == 69 bits; only need 63) this._Write(VALUE_CONSTANTS.Long, (byte)i, b8, b7, b6, b5, b4, b3, b2, b1, b0); }