/* Thor Server 2.0 Project - Codenamed "Stockholm" Copyright 2008 - 2009 Joe Hegarty This file is part of The Thor Server 2.0 Project - Codenamed "Stockholm". The Thor Server 2.0 Project - Codenamed "Stockholm" is free software: you can redistribute it and/or modify it under the terms of the Microsoft Public License The Thor Server Project is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Microsoft Public License for more details. You should have received a copy of the Microsoft Public License along with The Thor Server Project. If not, see http://www.opensource.org/licenses/ms-pl.html */ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace StockholmLibrary.Net { //------------------------------------ public static class VL64Encoding { //********************************************** public static byte[] EncodeInt(int inputValue) { int x = 0; return EncodeInt(inputValue, out x); } //********************************************** public static byte[] EncodeInt(int inputValue, out int size) { byte[] wf = new byte[6]; int pos = 0; int startPos = pos; int bytes = 1; int negativeMask = inputValue >= 0 ? 0 : 4; inputValue = Math.Abs(inputValue); wf[pos++] = (byte)(64 + (inputValue & 3)); for (inputValue >>= 2; inputValue != 0; inputValue >>= 6) { bytes++; wf[pos++] = (byte)(64 + (inputValue & 0x3f)); } wf[startPos] = (byte)(wf[startPos] | bytes << 3 | negativeMask); byte[] result = new byte[pos]; for (int x = 0; x < pos; ++x) { result[x] = wf[x]; } size = pos; return result; } //********************************************** public static int DecodeInt(byte[] raw) { int pos = 0; int v = 0; bool negative = (raw[pos] & 4) == 4; int totalBytes = raw[pos] >> 3 & 7; v = raw[pos] & 3; pos++; int shiftAmount = 2; for (int b = 1; b < totalBytes; b++) { v |= (raw[pos] & 0x3f) << shiftAmount; shiftAmount = 2 + 6 * b; pos++; } if (negative == true) { v *= -1; } return v; } } }