/* Blunk - Multi User Server Framework Copyright 2009 - 2010 Nils W [nillus.net] Michael Graham [script-o-matic.net] This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program 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 GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . * PORTED TO C# BY awa500! */ using System; /** * Provides methods for working with bits, bytes etc. * * @author Nillus * */ namespace Holo.Source.Socket_servers.MUS { public class BitUtil { public static int NUMBER_OF_BITS_IN_A_BYTE = 8; public static short MASK_TO_BYTE = 0xFF; public static int SIZE_OF_AN_INT_IN_BYTES = 4; public static byte[] intToBytes(int i) { byte[] bytes = new byte[4]; /* bytes[0] = (byte)(i & MASK_TO_BYTE); i >>= NUMBER_OF_BITS_IN_A_BYTE; bytes[1] = (byte)(i & MASK_TO_BYTE); i >>= NUMBER_OF_BITS_IN_A_BYTE; bytes[2] = (byte)(i & MASK_TO_BYTE); i >>= NUMBER_OF_BITS_IN_A_BYTE; bytes[3] = (byte)(i & MASK_TO_BYTE); */ bytes[3] = (byte)(i & MASK_TO_BYTE); i >>= NUMBER_OF_BITS_IN_A_BYTE; bytes[2] = (byte)(i & MASK_TO_BYTE); i >>= NUMBER_OF_BITS_IN_A_BYTE; bytes[1] = (byte)(i & MASK_TO_BYTE); i >>= NUMBER_OF_BITS_IN_A_BYTE; bytes[0] = (byte)(i & MASK_TO_BYTE); return bytes; } public static int bytesToInt(byte A, byte B, byte C, byte D) { int i = (D & MASK_TO_BYTE); i |= ((C & MASK_TO_BYTE) << 8); i |= ((B & MASK_TO_BYTE) << 16); i |= ((A & MASK_TO_BYTE) << 24); return i; } public static int bytesToInt(byte[] bytes) { return bytesToInt(bytes[0], bytes[1], bytes[2], bytes[3]); } //public static short bytesToShort(byte A, byte B) //{ // short i = (short)(B & MASK_TO_BYTE); // i |= ((A & MASK_TO_BYTE) << 8); // return i; //} public static byte[] getEvenStringBytes(string s) { return padByteArrayEven(System.Text.Encoding.Default.GetBytes(s)); } public static byte[] padByteArrayEven(byte[] src) { // Is not even? if(src.Length % 2 == 0) return src; else { byte[] outB = new byte[src.Length + 1]; for(int i = 0; i < outB.Length - 1; i++) { outB[i] = src[i]; } // So there's an added NULL byte return outB; } } } }