internal virtual void DoPrevSetBit(BitArray a, LongBitSet b) { int aa = a.Count + Random().Next(100); long bb = aa; do { //aa = a.PrevSetBit(aa-1); aa--; while ((aa >= 0) && (!a.SafeGet(aa))) { aa--; } if (b.Length() == 0) { bb = -1; } else if (bb > b.Length() - 1) { bb = b.PrevSetBit(b.Length() - 1); } else if (bb < 1) { bb = -1; } else { bb = bb >= 1 ? b.PrevSetBit(bb - 1) : -1; } Assert.AreEqual(aa, bb); } while (aa >= 0); }
public override System.Collections.BitArray Bits(IndexReader reader) { object coreKey = reader.GetFieldCacheKey(); object delCoreKey = reader.HasDeletions() ? reader.GetDeletesCacheKey() : coreKey; object cached = cache.Get(reader, coreKey, delCoreKey); if (cached != null) { if (cached is System.Collections.BitArray) { return((System.Collections.BitArray)cached); } else if (cached is DocIdBitSet) { return(((DocIdBitSet)cached).GetBitSet()); } // It would be nice to handle the DocIdSet case, but that's not really possible } System.Collections.BitArray bits = filter.Bits(reader); if (bits != null) { cache.Put(coreKey, delCoreKey, bits); } return(bits); }
private ADNode MakeADTree(int i, BitArray recordNums, int depth, Varset variables) { // since this is index i, there are (variableCount - i) remaining variables. // therefore, it will have that many children int count = 0; for(int idx = 0; idx < recordNums.Count; idx++) { if (recordNums[idx]) { count += 1; } } ADNode adn = new ADNode(network.Size() - i, count); // check if we should just use a leaf list if (adn.Count < rMin) { BitArray leafList = new BitArray(recordNums); adn.LeafList = leafList; return adn; } // for each of the remaining variables for (int j = i; j < network.Size(); j++) { // create a vary node variables.Set(j, true); Varset newVariables = new Varset(variables); VaryNode child = MakeVaryNode(j, recordNums, depth, newVariables); adn.SetChild(j - i, child); } return adn; }
/// <summary> /// 获取整数的位状态 /// </summary> /// <param name="data">传送过来的整数</param> /// <param name="bitNo">转换成二进制后,指定的第几位,0表示由右至左的最右边的第一位,范围为0-31</param> /// <returns>返回指定的位状态,true表示为1,false表示为0</returns> public static bool GetBit(int data, int bitNo) { int[] bta = new int[1]; bta[0] = data; System.Collections.BitArray myBA = new System.Collections.BitArray(bta); return(myBA.Get(bitNo)); }
private List<BigInteger> GeneratePrimes(int max) { List<BigInteger> result = new List<BigInteger>(); BitArray sieve = new BitArray(max, true); for (int i = 2; i < Math.Sqrt(max) + 1; i++) { if (!sieve[i]) { continue; } for (int j = i * i; j < max; j += i) { sieve[j] = false; } } for (int i = 2; i < max; i++) { if (sieve[i]) { result.Add(i); } } return result; }
private List <int> GetAllPrimes(int max) { var vals = new List <int>((int)(max / (Math.Log(max) - 1.08366))); var maxSquareRoot = Math.Sqrt(max); var eliminated = new System.Collections.BitArray(max + 1); vals.Add(2); for (var i = 3; i <= max; i += 2) { if (eliminated[i]) { continue; } if (i < maxSquareRoot) { for (var j = i * i; j <= max; j += 2 * i) { eliminated[j] = true; } } vals.Add(i); } return(vals); }
/// <summary> /// Returns a string representation of the BitArray object. /// </summary> /// <param name="bits">The BitArray object to convert to string.</param> /// <returns>A string representation of the BitArray object.</returns> public static string ToString(System.Collections.BitArray bits) { System.Text.StringBuilder s = new System.Text.StringBuilder(); if (bits != null) { for (int i = 0; i < bits.Length; i++) { if (bits[i] == true) { if (s.Length > 0) { s.Append(", "); } s.Append(i); } } s.Insert(0, "{"); s.Append("}"); } else { s.Insert(0, "null"); } return(s.ToString()); }
/* // It mutates the Chromosome // // @input probability is a double >=0 and <=100 */ public bool Mutate(double probability) { if (probability < 0) probability = 0; if (probability > 100) probability = 100; bool isMutated = false; for (int counter = 0; counter<nucleotideList.Count; counter++) { byte myByte = nucleotideList[counter]; //var bits = new BitArray(myByte); var bits = new BitArray(new byte[] { myByte }); //Cycle for change the single bit of the DNA for (int i = 0; i < bits.Length; i++) { Random r = new Random(Guid.NewGuid().GetHashCode()); if (r.NextDouble() < (probability / 100)) { bits[i] = !bits[i]; //the mutation switch the bit isMutated = true; } } //From BitArray to Byte[] byte[] ret = new byte[bits.Length / 8]; bits.CopyTo(ret, 0); //Assigning the new Byte[] to the nucleotide nucleotideList[counter] = ret[0]; } return isMutated; }
public Chromosome(int length) { Data = new BitArray(length); Random rand = new Random(); for(int i = 0; i<length; i++) Data.Set(i,rand.Next(2) == 1); }
public void Elements() { Triple <int, string, double> p1 = new Triple <int, string, double>(); string s = new string('z', 3); p1.First = 217; p1.Second = s; p1.Third = 3.14; Assert.AreEqual(217, p1.First); Assert.AreSame(s, p1.Second); Assert.AreEqual(3.14, p1.Third); object o = new System.Collections.BitArray(4); Triple <string, int, object> p2 = new Triple <string, int, object>("hello", 1, new System.Text.StringBuilder()); p2.Second = 212; p2.First = s; p2.Third = o; Assert.AreEqual(212, p2.Second); Assert.AreSame(s, p2.First); Assert.AreSame(o, p2.Third); p2.First = null; Assert.IsNull(p2.First); p2.Third = null; Assert.IsNull(p2.Third); }
public static DoseValue CalculateMeanDose(PlanSetup plan, Structure structure) { Dose dose = plan.Dose; if (dose == null) { return(new DoseValue(Double.NaN, DoseValue.DoseUnit.Unknown)); } plan.DoseValuePresentation = DoseValuePresentation.Absolute; double sum = 0.0; int count = 0; double xres = 2.5; double yres = 2.5; double zres = 2.5; int xcount = (int)((dose.XRes * dose.XSize) / xres); System.Collections.BitArray segmentStride = new System.Collections.BitArray(xcount); double[] doseArray = new double[xcount]; DoseValue.DoseUnit doseUnit = dose.DoseMax3D.Unit; for (double z = 0; z < dose.ZSize * dose.ZRes; z += zres) { for (double y = 0; y < dose.YSize * dose.YRes; y += yres) { VVector start = dose.Origin + dose.YDirection * y + dose.ZDirection * z; VVector end = start + dose.XDirection * dose.XRes * dose.XSize; SegmentProfile segmentProfile = structure.GetSegmentProfile(start, end, segmentStride); DoseProfile doseProfile = null; for (int i = 0; i < segmentProfile.Count; i++) { if (segmentStride[i]) { if (doseProfile == null) { doseProfile = dose.GetDoseProfile(start, end, doseArray); } double doseValue = doseProfile[i].Value; if (!Double.IsNaN(doseValue)) { sum += doseProfile[i].Value; count++; } } } doseProfile = null; } } double mean = sum / ((double)count); return(new DoseValue(mean, doseUnit)); }
/// <summary> /// 将一个BitArray拼接在当前对象之前 /// </summary> /// <param name="current"></param> /// <param name="before"></param> /// <returns></returns> public static BitArray Prepend(this BitArray current, BitArray before) { var bools = new bool[current.Length + before.Length]; before.CopyTo(bools, 0); current.CopyTo(bools, before.Length); return new BitArray(bools); }
public static int[] ESieve(int upperLimit) { int sieveBound = (int)(upperLimit - 1) / 2; int upperSqrt = ((int)Math.Sqrt(upperLimit) - 1) / 2; BitArray PrimeBits = new BitArray(sieveBound + 1, true); for (int i = 1; i <= upperSqrt; i++) { if (PrimeBits.Get(i)) { for (int j = i * 2 * (i + 1); j <= sieveBound; j += 2 * i + 1) { PrimeBits.Set(j, false); } } } List<int> numbers = new List<int>((int)(upperLimit / (Math.Log(upperLimit) - 1.08366))); numbers.Add(2); for (int i = 1; i <= sieveBound; i++) { if (PrimeBits.Get(i)) { numbers.Add(2 * i + 1); } } return numbers.ToArray(); }
public CompleteGraph(int n) { if (n <= 0) throw new ArgumentOutOfRangeException("[CompleteGraph Constructor] Input size of CompleteGraph must be positive"); this.nodes = n; this.edges = new BitArray(n * (n - 1) / 2); }
public ArrayFieldOfView(IFovBoard<IHex> board) { _isOnboard = h => board.IsOnboard(h); _fovBacking = new BitArray[board.MapSizeHexes.Width]; for (var i = 0; i < board.MapSizeHexes.Width; i++) _fovBacking[i] = new BitArray(board.MapSizeHexes.Height); }
/// <summary> /// get the B&W 1BPP bitmap for a bmp file /// </summary> /// <param name="bmpFileName"> /// </param> /// <returns> /// </returns> private static BitmapDotData GetBitmapData(string bmpFileName) { Image img = new Bitmap(bmpFileName); using (var bitmap = new Bitmap(img))// (Bitmap)Bitmap.FromFile(bmpFileName)) { var threshold = 127; var index = 0; var dimensions = bitmap.Width * bitmap.Height; var dots = new BitArray(dimensions); for (var y = 0; y < bitmap.Height; y++) { for (var x = 0; x < bitmap.Width; x++) { var color = bitmap.GetPixel(x, y); var luminance = (int)(color.R * 0.3 + color.G * 0.59 + color.B * 0.11); dots[index] = (luminance < threshold); index++; } } return new BitmapDotData() { Dots = dots, Height = bitmap.Height, Width = bitmap.Width }; } }
public SlabAllocator(int pageSize, int pageCount) { _pageSize = pageSize; _totalSize = pageCount * pageSize; _allocationMap = new BitArray(pageCount); }
protected override bool Key_Conform(String Key) { byte[] Key_in_Bytes = System.Text.UTF8Encoding.Default.GetBytes(Key); BitArray Key_in_Bits = new System.Collections.BitArray(Key_in_Bytes); return(Key_in_Bits.Length == length_Key_in_Bits); }
private void erose(BitArray bufferSrc, BitArray bufferDst) { for (int row = 0; row < height; row++) { for (int col = 0; col < width; col++) { int index = row * width + col; bufferDst[index] = true; for (int i = 0; i < 9; i++) { int neighborRow = row + neighborOffset[i, 1]; int neighborCol = col + neighborOffset[i, 0]; if (neighborRow < 0 || neighborRow >= height || neighborCol < 0 || neighborCol >= width) { //treat border as false bufferDst[index] = false; break; } if (!bufferSrc[neighborRow * width + neighborCol]) { bufferDst[index] = false; break; } } } } }
static IList<string> GetCombines(string str) { var result = new List<string>(); var arr = str.Split(','); var numItem = arr.Length; for (int i = 1; i <= Math.Pow(2, numItem); i++) { string temp = null; BitArray b = new BitArray(new int[] { i }); for (int j = 0; j < numItem; j++) { if (b[j]) { if (temp != null) { temp += ","; } temp += arr[j]; } } if (!string.IsNullOrEmpty(temp)) { result.Add(temp); } } return result; }
private void CreateTree() { BitArray countIndices = new BitArray(recordCount); countIndices.SetAll(true); Varset empty = new Varset(network.Size()); root = MakeADTree(0, countIndices, 0, empty); }
public static bool verificarPermissao(Type tipoEntidadeVerificar, string chavePerfilCripto) { bool resultadoVerificacao = false; BitArray arrayChaveDecripto = null; byte[] preChavePerfilDecripto = new byte[ControladorAcesso.tamanhoChavePerfil]; bool[] chavePerfilDecripto = new bool[ControladorAcesso.tamanhoChavePerfil]; Criptografador cripto = new Criptografador(); preChavePerfilDecripto = cripto.decriptografarTexto(ref chavePerfilCripto); arrayChaveDecripto = new BitArray(preChavePerfilDecripto); arrayChaveDecripto.Length = ControladorAcesso.tamanhoChavePerfil; arrayChaveDecripto.CopyTo(chavePerfilDecripto, 0); foreach (object atributo in tipoEntidadeVerificar.GetCustomAttributes(true)) if (atributo.GetType().Name.Equals("PerfilAcesso")) { long CodigoPerfil = long.Parse(atributo.GetType().GetField("CodigoPerfil"). GetValue(atributo).ToString()); resultadoVerificacao = chavePerfilDecripto[CodigoPerfil]; break; } return resultadoVerificacao; }
private void button1_Click(object sender, EventArgs e) { Int32 i = 0; richTextBox1.Text = ""; //HuffmanTree htree = new HuffmanTree(); htree.Build(textBox1.Text); encoded = htree.Encode(textBox1.Text); MessageBox.Show("Закодировано"); foreach (bool bit in encoded) { richTextBox1.Text += ((bit ? 1 : 0).ToString() + " "); } foreach (KeyValuePair<char, int> item in htree.Frequencies) { Debug.Assert( richTextBox3 != null, "richTextBox3 != null" ); List<String> list = new List<String>(); foreach (String s in htree.Codec) { list.Add( s ); } if (list.ToArray().Length > i) { richTextBox3.Text += (@"Символ: " + item.Key + @" Количество: " + item.Value.ToString() + @" Частота: " + Round( value: (float)item.Value / textBox1.Text.Length, digits: 3) + @" Код " + list.ToArray()[i] + "\n"); } Int32 i1 = i++; } String originalText = textBox1.Text; int countSimbol = originalText.Length; int summ = countSimbol * 8; textBox2.Text = Convert.ToString(summ); }
public static bool[] GetBoolArrayFromByte(byte[] bytes) { bool[] bools = new bool[bytes.Length * 8]; BitArray bits = new BitArray(bytes); bits.CopyTo(bools, 0); return bools; }
internal AsyncResult(string message, int ftpCode, int result) { m_result = new BitArray(3); m_message = message; m_ftpResponse = ftpCode; m_result[result] = true; }
public byte[] Serialize(string s) { var ba = new System.Collections.BitArray(s.Length * Base); int pos = 0; foreach (var c in s) { int mask = 1; int val = chars.IndexOf(c) + 1; if (val == 0) { throw new ArgumentException(); } for (int i = 0; i < Base; i++) { if ((val & mask) > 0) { ba[pos] = true; } mask <<= 1; pos++; } } int len = (int)Math.Ceiling((ba.Length + Base) / 8d); byte[] arr = new byte[len]; ba.CopyTo(arr, 0); return(arr); }
private void ShowOutputBits(ulong x) { textBox4.Clear(); // X:\jsc.svn\examples\javascript\test\TestULongToByteCast\TestULongToByteCast\Application.cs var a = BitConverter.GetBytes(x); foreach (var _byte in a.Reverse()) { var bits = new System.Collections.BitArray(new[] { _byte }); for (int index = 7; index >= 0; index--) { var bit = bits[index]; if (bit) { textBox4.AppendText("1"); } else { textBox4.AppendText("0"); } } textBox4.AppendText(" "); } }
public BitArray(int sizeX, int sizeY) { sizeX = Math.Max(sizeX, 0); sizeY = Math.Max(sizeY, 0); this.size = new [] { sizeX, sizeY, 1 }; data = new System.Collections.BitArray(sizeX * sizeY); }
static ArrayList sieve(int arg_max_prime) { BitArray al = new BitArray(arg_max_prime, true); int lastprime = 1; int lastprimeSquare = 1; while (lastprimeSquare <= arg_max_prime) { lastprime++; while (!(bool)al[lastprime]) lastprime++; lastprimeSquare = lastprime * lastprime; for (int i = lastprimeSquare; i < arg_max_prime; i += lastprime) if (i > 0) al[i] = false; } ArrayList sieve_2_return = new ArrayList(); for (int i = 2; i < arg_max_prime; i++) if (al[i]) sieve_2_return.Add(i); return sieve_2_return; }
private void Setup() { // Fill Bit arrays chka = new[] { flag_0001,flag_0002,flag_0003,flag_0004,flag_0005, flag_2237,flag_2238,flag_2239, flag_0115,flag_0963, // Mewtwo flag_0114,flag_0790, // Zygarde flag_0285,flag_0286,flag_0287,flag_0288,flag_0289, // Statuettes flag_0290,flag_0291,flag_0292,flag_0293,flag_0294, // Super Unlocks flag_0675, // Chatelaine 50 flag_2546, // Pokedex }; byte[] data = new byte[0x180]; Array.Copy(Main.SAV.Data, Main.SAV.EventFlag, data, 0, 0x180); BitArray BitRegion = new BitArray(data); BitRegion.CopyTo(flags, 0); // Setup Event Constant Editor CB_Stats.Items.Clear(); for (int i = 0; i < Constants.Length; i += 2) { CB_Stats.Items.Add($"0x{i.ToString("X3")}"); Constants[i / 2] = BitConverter.ToUInt16(Main.SAV.Data, Main.SAV.EventConst + i); } CB_Stats.SelectedIndex = 0; // Populate Flags setup = true; popFlags(); }
protected override AnalogicDataRegisterDE ReadValues(FileStream fstream, string Name, long HeaderLen, DateTime dateHourMinute) { AnalogicDataRegisterDE measurement; DateTime DataDosValores; char[] Dbuffer; BitArray myBA; fstream.Position = HeaderLen - DataDosValoresLen; Dbuffer = new char[DataDosValoresLen]; r.Read(Dbuffer,0,DataDosValoresLen); DataDosValores = ConvertDateTime.DateVmsToDateTime(Dbuffer,"pt-BR"); fstream.Position = HeaderLen + ((int) htHeader[Name] * NumBValGr); float measAux = r.ReadSingle(); float estimAux = r.ReadSingle(); byte[] BBuffer = new byte[NumBValGr - 8]; BBuffer = r.ReadBytes(NumBValGr - 8); if(BBuffer.Length > 1) { byte[] aux = new byte[1]; aux[0] = BBuffer[1]; myBA = new BitArray(aux); } else myBA = new BitArray(BBuffer); if(DataDosValores.Date == dateHourMinute.Date) measurement = new AnalogicDataRegisterDE(dateHourMinute,Name,measAux,estimAux,myBA); else measurement = new AnalogicDataRegisterDE(Name,dateHourMinute,true); return measurement; }
private static void WriteBitArray(ObjectWriter writer, BitArray bitArray) { // Our serialization format doesn't round-trip bit arrays of non-byte lengths Contract.ThrowIfTrue(bitArray.Length % 8 != 0); writer.WriteInt32(bitArray.Length / 8); // This will hold the byte that we will write out after we process every 8 bits. This is // LSB, so we push bits into it from the MSB. byte b = 0; for (var i = 0; i < bitArray.Length; i++) { if (bitArray[i]) { b = (byte)(0x80 | b >> 1); } else { b >>= 1; } if ((i + 1) % 8 == 0) { // End of a byte, write out the byte writer.WriteByte(b); } } }
public static Byte[] GenerateHeader(Boolean fin, Boolean rsv1, Boolean rsv2, Boolean rsv3, Boolean opt4, Boolean opt3, Boolean opt2, Boolean opt1, Boolean mask) { Boolean[] header1 = new Boolean[8]; header1[7] = fin; header1[6] = rsv1; header1[5] = rsv2; header1[4] = rsv3; header1[3] = opt4; header1[2] = opt3; header1[1] = opt2; header1[0] = opt1; Boolean[] header2 = new Boolean[8]; header2[7] = mask; header2[6] = false; header2[5] = false; header2[4] = false; header2[3] = false; header2[2] = false; header2[1] = false; header2[0] = false; BitArray bitArray1 = new BitArray(header1); Byte[] byteHead = new Byte[2]; bitArray1.CopyTo(byteHead, 0); BitArray bitArray2 = new BitArray(header2); bitArray2.CopyTo(byteHead, 1); return byteHead; }
/// <summary> /// Get bytes array from Boolean values. /// </summary> /// <param name = "array">Array to be packed</param> /// <returns>Bytes array</returns> public static byte[] GetByteArrayFromBool(bool[] array) { BitArray b = new BitArray(array); byte[] bytesArr = new byte[array.Length / 8]; b.CopyTo(bytesArr, 0); return bytesArr; }
public Player(ContentManager Content, ParticleTools particleTools, GameUnit x, GameUnit y) : base(CollisionType.StickyCollision) { sprites = new Dictionary<SpriteState, Sprite>(); InitializeSprites(Content); this.particleTools = particleTools; kinematicsX = new Kinematics(x, 0); kinematicsY = new Kinematics(y, 0); accelerationX = 0; horizontalFacing = SpriteState.HorizontalFacing.Left; intendedVerticalFacing = SpriteState.VerticalFacing.Horizontal; walkingAnimation = new WalkingAnimation(); maybeGroundTile = null; jumpActive = false; playerHealth = new PlayerHealth(Content); interacting = false; invincibleTimer = new Timer(InvincibleTime); damageText = new FloatingNumber(Content, FloatingNumber.NumberType.Damage); experienceText = new FloatingNumber(Content, FloatingNumber.NumberType.Experience); gunExperienceHud = new GunExperienceHud(Content); polarStar = new PolarStar(Content); collisionRectangle = new CompositeCollisionRectangle(new Rectangle((int)Math.Round(CollisionTopLeft), (int)Math.Round(CollisionYTop), (int)Math.Round(CollisionTopWidth), (int)Math.Round(CollisionYHeight / 2)), new Rectangle((int)Math.Round(CollisionBottomLeft), (int)Math.Round(CollisionYTop + CollisionYHeight / 2), (int)Math.Round(CollisionBottomWidth), (int)Math.Round(CollisionYHeight / 2)), new Rectangle(6, 10, 10, 12), new Rectangle(16, 10, 10, 12)); }
private void TM1638ButtonsMessageReader(IList<int> messageData) { int readPos = 1; for (int u = 1; u <= this.numberUnits; u++) { if (this.tm1640Units[u - 1]) { continue; } this.buttonsRead = messageData[readPos++]; if (this.buttonsRead != -1) { this.butByte[0] = Convert.ToByte(this.buttonsRead); this.buttons = new BitArray(this.butByte); for (var i = 0; i < Constants.NumberButtonsOnTm1638; i++) { if (this.buttons[i]) { if (this.ButtonPress == null) throw new ArgumentNullException(); ButtonPressEventHandler temp = this.ButtonPress; if (temp != null) { temp(u, i+1); } } } } } }
/// <summary> /// Get bytes bools from Boolean values. /// </summary> /// <param name = "bools">Array to be packed</param> /// <returns>Bytes bools</returns> public static byte[] GetByteArrayFromBool(bool[] bools) { BitArray bits = new BitArray(bools); byte[] bytes = new byte[bools.Length / 8]; bits.CopyTo(bytes, 0); return bytes; }
public void calcHydrogenBonds(System.Collections.BitArray bsA, BitArray bsB) { for (int i = modelCount; --i >= 0;) { models[i].calcHydrogenBonds(bsA, bsB); } }
/// <summary> /// aaa -> 000aaa /// </summary> /// <param name="to">Reference to array to put the result</param> /// <param name="bitArray">Array from where to put</param> /// <param name="p">Size of the new array</param> private void ExtendToSizeRight(ref BitArray to, BitArray bitArray, int p) { if (to == null) to = new BitArray(p, false); for (int i = 0; i < bitArray.Length; i++) to[i] = bitArray[i]; }
public void CreateFromBitArrMix() { int h = 3; int w = 3; string filename = "pmmtest3"; BitArray ba = new BitArray(w * h); for (int i = 2; i < ba.Count; i++) ba[i] = true; PPM.createFromBitArr(filename, ba, 3, 3); StreamReader sr = new StreamReader(filename + ".ppm"); //PPM Header Assert.AreEqual(sr.ReadLine(), "P3"); Assert.AreEqual(sr.ReadLine(), "# CREATOR: GIMP PNM Filter Version 1.1"); Assert.AreEqual(sr.ReadLine(), w + " " + h); Assert.AreEqual(sr.ReadLine(), "255"); //Test Data for (int i = 0; i < 12; i++) { Assert.AreEqual(sr.ReadLine(), "255"); //Since Outline gets cleared } for (int i = 0; i < 3; i++) { Assert.AreEqual(sr.ReadLine(), "0"); //Middle Point } for (int i = 0; i < 12; i++) { Assert.AreEqual(sr.ReadLine(), "255"); //Since Outline gets cleared } sr.Close(); File.Delete(filename + ".ppm"); }
public byte[] byteToHexToByteArray(byte c) { BitArray ba = new BitArray(BitConverter.GetBytes(c)); BitArray bl = new BitArray(4); BitArray bh = new BitArray(4); for (int i = 0; i < 4; i++) { bh[i] = ba[4 + i]; bl[i] = ba[i]; } byte h = ConvertToByte(bh); byte l = ConvertToByte(bl); if (h > (byte)9) h += (byte)55; else h += (byte)48; if (l > (byte)9) l += (byte)55; else l += (byte)48; byte[] tab = new byte[2]; tab[0] = h; tab[1] = l; return tab; }
public override void Write(byte value) { ba = new BitArray(new byte[] { value }); for (byte i = 0; i < 8; i++) { Write(ba[i]); } }
static void DisplayBits(Col.BitArray bitArray) { foreach (bool bit in bitArray) { Cons.Write($"{(bit? 1 : 0)}"); } Cons.WriteLine(); }
public void DebuggerProxy_FrameworkTypes_BitArray() { // BitArray doesn't have debugger proxy/display var obj = new System.Collections.BitArray(new int[] { 1 }); var str = CSharpObjectFormatter.Instance.FormatObject(obj, s_inline); Assert.Equal("BitArray(32) { true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false }", str); }
virtual public void SetCapacity(int capacity) { if (null == this.dbNullBits) { this.dbNullBits = new BitArray(capacity); } else { this.dbNullBits.Length = capacity; } }
// Crypt_Decrypt_Specific_Algo is a factorisation of the code use by Encrypt_Specific_Algo and Decrypt_Specific_Algo // The encryption and decryption algo are the same, the only change is the order of the keys protected String Crypt_Decrypt_Specific_Algo(String Text, String Key, Boolean encrypt) { const String _NULL_VALUE_ = "<NULL>";// this constante is use to replace the '\0' char (since we won't be able to read the \0 char again for decoding) const int Message_Blocks_Lenght = 64; String Coded_text_String = ""; byte[] TempoBytes = System.Text.UTF8Encoding.Default.GetBytes(Key); BitArray Key_in_Bits = new System.Collections.BitArray(TempoBytes); change_Least_Significant_Bit_position(Key_in_Bits);// change MSB and LSB positions to make it more conveniant for the rest of the algo BitArray[] Ki = Partial_Keys_Creation(Key_in_Bits); if (encrypt) { Array.Reverse(Ki); //the order of the keys are change if we want to decrypt } Text = Text.Replace(_NULL_VALUE_, "\0"); while (Text.Length % 8 != 0) // Add bytes to the message (if necessary) { Text += " "; } TempoBytes = System.Text.UTF8Encoding.Default.GetBytes(Text); BitArray Source_Text_in_Bits = new System.Collections.BitArray(TempoBytes); change_Least_Significant_Bit_position(Source_Text_in_Bits); // divid message in part of 64 bits for (int i = 0; i < Source_Text_in_Bits.Length / Message_Blocks_Lenght; i++) { // Initial permutation PI on the message + split it in two parts, the left part and the rigth part BitArray L = new BitArray(Message_Blocks_Lenght / 2); BitArray R = new BitArray(Message_Blocks_Lenght / 2); for (int j = 0; j < (Message_Blocks_Lenght / 2); j++) { L[j] = Source_Text_in_Bits[IP[j] - 1 + i * 64]; } for (int j = (Message_Blocks_Lenght / 2); j < (Message_Blocks_Lenght); j++) { R[j - (Message_Blocks_Lenght / 2)] = Source_Text_in_Bits[IP[j] - 1 + i * 64]; } Feistel_Algo(L, R, Ki); // switch and aggregate the left and rigth parts + final permutation IP^(-1) on the coded message BitArray Coded_text_In_Bits = new BitArray(64); for (int j = 0; j < FP.Length; j++) { Coded_text_In_Bits[j] = (FP[j] - 1) < R.Length ? R[FP[j] - 1] : L[FP[j] - 1 - R.Length]; } // convert bits to String byte[] Coded_text_In_Bytes = new byte[Coded_text_In_Bits.Length / 8]; change_Least_Significant_Bit_position(Coded_text_In_Bits);//Put back the MSB and LSB in the order .Net is use to Coded_text_In_Bits.CopyTo(Coded_text_In_Bytes, 0); Coded_text_String = Coded_text_String + System.Text.UTF8Encoding.Default.GetString(Coded_text_In_Bytes); } return(Coded_text_String.Replace("\0", _NULL_VALUE_)); //return Coded_text_String; }
public override void Write(ushort value) { ba = new BitArray(BitConverter.GetBytes(value)); for (byte i = 0; i < 16; i++) { this.Write(ba[i]); } ba = null; }
public static void EachBit(this Type.BitArray instance, EachItemAction <bool> action) { int bitCount = instance.Length; for (int index = 0; index < bitCount; index++) { action(instance.Get(index), index); } }
/// <summary> /// Returns the index of the first bit that is set to true that occurs /// on or after the specified starting index. If no such bit exists /// then -1 is returned. /// </summary> /// <param name="bits">The BitArray object.</param> /// <param name="fromIndex">The index to start checking from (inclusive).</param> /// <returns>The index of the next set bit.</returns> public static int NextSetBit(System.Collections.BitArray bits, int fromIndex) { for (int i = fromIndex; i < bits.Length; i++) { if (bits[i] == true) { return(i); } } return(-1); }
public virtual void SetCapacity(int capacity) { if (null == _dbNullBits) { _dbNullBits = new BitArray(capacity); } else { _dbNullBits.Length = capacity; } }
static public int get_IsSynchronized(IntPtr l) { try { System.Collections.BitArray self = (System.Collections.BitArray)checkSelf(l); pushValue(l, true); pushValue(l, self.IsSynchronized); return(2); } catch (Exception e) { return(error(l, e)); } }
/// <summary> /// 根据给定的32位整数,返回这32位中每一位的状态值 /// </summary> /// <param name="data">指定32位整数</param> /// <returns>返回表示每一位状态信息的数组</returns> public static bool[] GetBit(int data) { bool[] stau = new bool[32]; int[] bta = new int[1]; bta[0] = data; System.Collections.BitArray myBA = new System.Collections.BitArray(bta); for (int i = 0; i < 32; i++) { stau[i] = myBA.Get(i); } return(stau); }
public BitArray(byte[] data) { System.Collections.BitArray temp = new System.Collections.BitArray(data); _data = new bool[temp.Length]; for (int i = 0; i < data.Length; i++) { for (int j = 0; j < 8; j++) { _data[8 * i + j] = (bool)temp[8 * i + (7 - j)]; } } }
/// <summary> /// Hamming weight, number of non zero elements /// </summary> /// <param name="bitArray"></param> /// <returns></returns> public static int Population(this System.Collections.BitArray bitArray) { int population = 0; for (int i = 0; i < bitArray.Count; i++) { if (bitArray[i] == true) { population++; } } return(population); }
/// <summary> /// Returns the number of bits set to true in this BitSet. /// </summary> /// <param name="bits">The BitArray object.</param> /// <returns>The number of bits set to true in this BitSet.</returns> public static int Cardinality(System.Collections.BitArray bits) { int count = 0; for (int i = 0; i < bits.Count; i++) { if (bits[i] == true) { count++; } } return(count); }
static public int GetEnumerator(IntPtr l) { try { System.Collections.BitArray self = (System.Collections.BitArray)checkSelf(l); var ret = self.GetEnumerator(); pushValue(l, true); pushValue(l, ret); return(2); } catch (Exception e) { return(error(l, e)); } }
static public int SetAll(IntPtr l) { try { System.Collections.BitArray self = (System.Collections.BitArray)checkSelf(l); System.Boolean a1; checkType(l, 2, out a1); self.SetAll(a1); pushValue(l, true); return(1); } catch (Exception e) { return(error(l, e)); } }
static public int set_Length(IntPtr l) { try { System.Collections.BitArray self = (System.Collections.BitArray)checkSelf(l); int v; checkType(l, 2, out v); self.Length = v; pushValue(l, true); return(1); } catch (Exception e) { return(error(l, e)); } }
// ------------------------------------------------------------------------ /// <summary>Sychnronous read digital inputs starting from a specified offset.</summary> /// <param name="module_nr">The position of the module.</param> /// <param name="offset">Starting offset for digital read command.</param> /// <param name="size">Number of bits to read.</param> /// <returns>Result of the read command as bool arrary.</returns> public bool[] ReadDigitalInputs(byte module_nr, ushort offset, ushort size) { byte[] values = { }; bool[] data = new bool[size]; if (ValidateData(module_nr, size)) { if (MDinfo[module_nr].digital_in_index != 0xFFFF) { if (size <= dig_in_buffer.Length - (MDinfo[module_nr].digital_in_index * 8 + offset)) { // ------------------------------------------------------------------------ // Request value from bus coupler if (_refresh == 0) { // Read digital inputs, convert data to bool array MBmaster.ReadDiscreteInputs(ID_value, 0, Convert.ToUInt16(MDinfo[module_nr].digital_in_index * 8 + offset), size, ref values); if ((values == null) && (OnBCexception != null)) { OnBCexception(excDataEmptyAnswer); } else { BitArray tmp1 = new System.Collections.BitArray(values); bool[] tmp2 = new bool[tmp1.Count]; tmp1.CopyTo(tmp2, 0); Array.Copy(tmp2, 0, data, 0, size); } } // ------------------------------------------------------------------------ // Request value from internal buffer else { Array.Copy(dig_in_buffer, MDinfo[module_nr].digital_in_index * 8 + offset, data, 0, size); } return(data); } else if (OnBCexception != null) { OnBCexception(excDataSize); } } else if (OnBCexception != null) { OnBCexception(excNoDigInData); } } return(null); }
public void AddBitsOf(HasseFingerprint F) { BitArray fp2 = ((HasseFingerprint)F).fp; if (fp == null) { fp = new System.Collections.BitArray(fp2); } else { fp.Or(fp2); } this.bitCount = this.CountBits(); }