public static byte[] Encode(ulong integer) { int requiredBytes; if (integer <= byte.MaxValue >> 2) /* 63 */ { requiredBytes = 1; } else if (integer <= ushort.MaxValue >> 2) /* 16383 */ { requiredBytes = 2; } else if (integer <= uint.MaxValue >> 2) /* 1073741823 */ { requiredBytes = 4; } else if (integer <= ulong.MaxValue >> 2) /* 4611686018427387903 */ { requiredBytes = 8; } else { throw new ArgumentOutOfRangeException(nameof(integer), "Value is larger than VariableInteger.MaxValue."); } var offset = 8 - requiredBytes; var uInt64Bytes = ByteUtilities.GetBytes(integer); var first = uInt64Bytes[offset]; first = (byte)(first | ((requiredBytes / 2) << 6)); uInt64Bytes[offset] = first; var result = new byte[requiredBytes]; Buffer.BlockCopy(uInt64Bytes, offset, result, 0, requiredBytes); return(result); }
public static byte[] Encode(UInt64 integer) { int requiredBytes = 0; if (integer <= byte.MaxValue >> 2) /* 63 */ { requiredBytes = 1; } else if (integer <= UInt16.MaxValue >> 2) /* 16383 */ { requiredBytes = 2; } else if (integer <= UInt32.MaxValue >> 2) /* 1073741823 */ { requiredBytes = 4; } else if (integer <= UInt64.MaxValue >> 2) /* 4611686018427387903 */ { requiredBytes = 8; } else { throw new ArgumentOutOfRangeException("Value is larger than VariableInteger.MaxValue."); } int offset = 8 - requiredBytes; byte[] uInt64Bytes = ByteUtilities.GetBytes(integer); byte first = uInt64Bytes[offset]; first = (byte)(first | (requiredBytes / 2) << 6); uInt64Bytes[offset] = first; byte[] result = new byte[requiredBytes]; Buffer.BlockCopy(uInt64Bytes, offset, result, 0, requiredBytes); return(result); }
public uint ReadUInt32() { return(ByteUtilities.ToUInt32(ReadBytes(4))); }
public ushort ReadUInt16() { var bytes = ReadBytes(2); return(ByteUtilities.ToUInt16(bytes)); }