public override string Solve(string input, bool part2) { long answerCnt = 0; foreach (string answerGroup in GetGroupedLines(input)) {//Get the group answerkey for each group. //Initialize the group key for the right operation below. int groupKey = part2 ? -1 : 0; foreach (string personAnswer in GetLines(answerGroup)) { //Get a single persons answers int answerKey = 0; foreach (Match answer in Regex.Matches(personAnswer.ToLower(), @"\w")) { answerKey = Bitwise.SetBit(answerKey, (byte)answer.Value[0] - (byte)'a', true); } //Add Persons answers to its group Key if (part2) { groupKey &= answerKey; } else { groupKey |= answerKey; } } //count the answers in this group answerCnt += Bitwise.CountSetBits(groupKey); } return("Sum of all Answers: " + answerCnt); }
private int ExecuteInterrupt() { IME = false; int pc = LoadRegister(Registers16Bit.PC); int sp = Bitwise.Wrap16(LoadRegister(Registers16Bit.SP) - 1); _gameboy.Mmu.WriteByte(pc >> 8, sp); int vector = 0; for (int i = 0; i < 5; i++) { if ((((_gameboy.Mmu.IE & _gameboy.Mmu.IF) >> i) & 0x01) == 1) { vector = 0x40 + (8 * i); _gameboy.Mmu.IF &= ~(0x1 << i); break; } } SetRegister(Registers16Bit.PC, vector); sp = Bitwise.Wrap16(sp - 1); _gameboy.Mmu.WriteByte(pc & 0xFF, sp); SetRegister(Registers16Bit.SP, sp); return(4); }
public override void Execute() { // Fetch operands List <byte[]> DestSource = Fetch(); // Determine the half-lengths of operands. This is because half of the capacity will be // for the modulo, the other for the dividend. int HalfLength = (int)Capacity; // Create a new array to store the result, which is two half lengths, it will have the quotient and modulo // copied into it. byte[] Result = new byte[(int)Capacity * 2]; // Two arrays to hold the quotient and modulo. byte[] Quotient; byte[] Modulo; // Perform the division Bitwise.Divide(DestSource[0], DestSource[1], (int)Capacity * 2, (Settings | OpcodeSettings.SIGNED) == Settings, out Quotient, out Modulo); // Copy the results into the result array. Array.Copy(Quotient, Result, HalfLength); Array.Copy(Modulo, 0, Result, HalfLength, HalfLength); // Set the result. This (should) be a split register handle, which will split the Result array in two and set // each of the destination operands(D:A) appropriately. Set(Result); }
public void Set(byte[] data) { // A method for setting the value of a register pointed to by the register handle. //This is completely normal most of the time, e.g instructions like MUL which produce a result size greater than that of the destination if ((int)Size != data.Length) { System.Array.Resize(ref data, (int)Size); } // Setting an upper byte register // See full explanations for the following in FetchOnce() if (data.Length == (int)RegisterCapacity.BYTE && Code > XRegCode.B && Table == RegisterTable.GP && (RexByte == REX.NONE || (Settings | RegisterHandleSettings.NO_REX) == Settings)) { // e.g AH has the same integer value as SP(SP has no higher bit register reference) so when 0b101 is accessed with byte width you need to sub 4 to get the // normal reg code for that reg then set higher bit ourselves . CurrentContext.Registers[Table, RegisterCapacity.WORD, Code - 4] = new byte[] { CurrentContext.Registers[Table, RegisterCapacity.WORD, Code - 4][0], data[0] }; } else { if (data.Length == 4) { data = Bitwise.ZeroExtend(data, 8); } CurrentContext.Registers[Table, (RegisterCapacity)data.Length, Code] = data; } }
//push imm8 is valid but not push r8 // no 8/32 bit mode for reg push public Push(DecodedTypes.IMyDecoded input, OpcodeSettings settings = OpcodeSettings.NONE) : base("PUSH", input, settings, // When pushing an immediate, the default(no prefix) is to push a immediate DWORD. // When pushing a register, the default is to push the QWORD register. A DWORD register cannot be pushed. // Both of these can however be WORD values if a SIZEOVR prefix is present. (input is DecodedTypes.Immediate) ? (ControlUnit.LPrefixBuffer.Contains(PrefixByte.SIZEOVR) ? RegisterCapacity.WORD : RegisterCapacity.DWORD) : (ControlUnit.LPrefixBuffer.Contains(PrefixByte.SIZEOVR) ? RegisterCapacity.WORD : RegisterCapacity.QWORD)) { Result = Fetch()[0]; // If an operand is a non-WORD/QWORD, it is sign extended to a QWORD // Here is a demonstration of this, // https://prnt.sc/outmtv // As you can see, 0x6A, which is PUSH IMM8, is sign extended to a QWORD. // https://prnt.sc/ouyxwd // Look at the points marked X. An immediate DWORD is pushed at 0x401035 then popped into RAX. // RAX became 0x12345678, the DWORD pushed, even though 0x1234 was pushed right before it. Intuition would // suggest that the value of RAX should be 0x123456781234, but as shown, 0x12345678 was extended to be a // QWORD rather than a DWORD. It is shown in the first screenshot that the bytes for an immediate DWORD push, // 68 78 56 34 12 // ^ // are used, so there is no kind of assembler interference happening. // Furthermore, this proves that immediate word pushes are not sign extended, even though the manual implies that // they ought to. As you can infer from the second screenshot, 0x1234 was popped into BX, then 0x*f2 was popped into // RCX. If 0x1234 had been extended, this would have been reflected in the value of RCX, as zeroes there would be zeroes // there, not the exact value pushed at 0x40102f. if (Result.Length == 1 || Result.Length == 4) { Result = Bitwise.SignExtend(Result, 8); } }
internal override void WriteByte(int address, int value) { switch (address) { case 0xFF20: LengthSet = (value & 0x3F); return; case 0xFF21: WriteEnvelope(value); return; case 0xFF22: DividingRatio = value & 0x07; ShiftWidth = Bitwise.IsBitOn(value, 3); ShiftFrequency = (value >> 4) & 0xF; return; case 0xFF23: LengthEnabled = Bitwise.IsBitOn(value, 6); if (Bitwise.IsBitOn(value, 7)) Enable(); return; } throw new InvalidOperationException(String.Format("Cannot write to memory address 0x{0:X4}", address)); }
/// <summary> /// Called by colliding with a Token (from Token's OnTriggerEnter) /// </summary> /// <param name="token">Token that was collected</param> public override void CollectToken(Token token) { // Handle what type of token was collected if (token.GetType().Equals(typeof(ArrowToken))) { // Find the running timer associated with the token TokenTimer t = timers.Find(i => i.ID.Equals(((ArrowToken)token).Type.ToString())); // If the token has not been collected yet if (t == null) { // Add a new Token Timer and initialize it TokenTimer tt = gameObject.AddComponent <TokenTimer>(); tt.Initialize(TokenTimer.TOKEN_INTERVAL, ((ArrowToken)token).Type.ToString()); // Make sure that the token is removed from the component when the timer times out tt.TimeOut += new TokenTimer.TimerEvent(RemoveToken); types = Bitwise.SetBit(types, (int)tt.TokenType); timers.Add(tt); } else { // Token has already been collected so we just need to reset the timer t.Reset(); } } }
protected void WriteEnvelope(int value) { VolumeSet = (value >> 4); EnvelopeAdd = Bitwise.IsBitOn(value, 3); EnvelopeTimeSet = value & 0x07; DAC = (value & 0xF8) != 0; }
public void TestKnightOnC5Moves() { var board = new Board(WriteMessageLine, long.MaxValue); board.SetPosition("4k3/pppppppp/8/2N5/8/3P4/PPP1PPPP/4K3 w - - 0 1"); var knightDestinations = Board.KnightMoveMasks[(int)Square.C5] & ~board.CurrentPosition.ColorOccupancy[(int)Color.White]; WriteMessageLine("Knight destinations = "); WriteMessageLine(Position.ToString(knightDestinations)); WriteMessageLine(); var expectedKnightDestinations = 0ul; Bitwise.SetBit(ref expectedKnightDestinations, Square.B7); Bitwise.SetBit(ref expectedKnightDestinations, Square.D7); Bitwise.SetBit(ref expectedKnightDestinations, Square.E6); Bitwise.SetBit(ref expectedKnightDestinations, Square.E4); Bitwise.SetBit(ref expectedKnightDestinations, Square.B3); Bitwise.SetBit(ref expectedKnightDestinations, Square.A4); Bitwise.SetBit(ref expectedKnightDestinations, Square.A6); WriteMessageLine("Expected knight destinations = "); WriteMessageLine(Position.ToString(expectedKnightDestinations)); WriteMessageLine(); Assert.That(knightDestinations, Is.EqualTo(expectedKnightDestinations)); }
public void AddArrowType(Enums.Arrows type) { if (type > 0 && type < Enums.Arrows.NumTypes) { // Find the running timer associated with the type //TokenTimer t = timers.Find(i => i.ID.Equals(type.ToString())); // If the type has not been added yet //if (t == null) //{ // Add a new Token Timer and initialize it // TokenTimer tt = gameObject.AddComponent<TokenTimer>(); // tt.Initialize(TokenTimer.TOKEN_INTERVAL, type.ToString()); // Make sure that the type is removed from the component when the timer times out // tt.TimeOut += new TokenTimer.TimerEvent(RemoveToken); types = Bitwise.SetBit(types, (int)type); numTokens++; // timers.Add(tt); //} //else //{ // Type has already been added so we just need to reset the timer // t.Reset(); //} } }
/// <summary> /// BITOP : https://redis.io/commands/bitop /// </summary> public Task <long> OperationAsync(Bitwise operation, RedisBit first, RedisBit?second = null, CommandFlags flags = CommandFlags.None) { var firstKey = first.Key; var secondKey = second?.Key ?? default; return(this.Connection.Database.StringBitOperationAsync(operation, this.Key, firstKey, secondKey, flags)); }
/// <summary> /// Sets bits in range as ulong. /// </summary> /// <param name="pos">Position in bit array.</param> /// <param name="value">Value of bits to set.</param> /// <param name="numBits">Number of bits to set (must be 1-64).</param> public void SetBits(int pos, ulong value, int numBits = 1) { CheckArgsUlong(pos, numBits); var idxB = pos >> 6; var shiftB = pos & 0x3f; if (shiftB + numBits <= 64) { var mask = 0xfffffffffffffffful >> (64 - numBits); Ptr[idxB] = Bitwise.ReplaceBits(Ptr[idxB], shiftB, mask, value); return; } var end = math.min(pos + numBits, Length); var idxE = (end - 1) >> 6; var shiftE = end & 0x3f; var maskB = 0xfffffffffffffffful >> shiftB; Ptr[idxB] = Bitwise.ReplaceBits(Ptr[idxB], shiftB, maskB, value); var valueE = value >> (64 - shiftB); var maskE = 0xfffffffffffffffful >> (64 - shiftE); Ptr[idxE] = Bitwise.ReplaceBits(Ptr[idxE], 0, maskE, valueE); }
/// <summary> /// Set bits to desired boolean value. /// </summary> /// <param name="pos">Position in bit array.</param> /// <param name="value">Value of bits to set.</param> /// <param name="numBits">Number of bits to set.</param> public void SetBits(int pos, bool value, int numBits) { CheckArgs(pos, numBits); var end = math.min(pos + numBits, Length); var idxB = pos >> 6; var shiftB = pos & 0x3f; var idxE = (end - 1) >> 6; var shiftE = end & 0x3f; var maskB = 0xfffffffffffffffful << shiftB; var maskE = 0xfffffffffffffffful >> (64 - shiftE); var orBits = (ulong)-Bitwise.FromBool(value); var orBitsB = maskB & orBits; var orBitsE = maskE & orBits; var cmaskB = ~maskB; var cmaskE = ~maskE; if (idxB == idxE) { var maskBE = maskB & maskE; var cmaskBE = ~maskBE; var orBitsBE = orBitsB & orBitsE; Ptr[idxB] = (Ptr[idxB] & cmaskBE) | orBitsBE; return; } Ptr[idxB] = (Ptr[idxB] & cmaskB) | orBitsB; for (var idx = idxB + 1; idx < idxE; ++idx) { Ptr[idx] = orBits; } Ptr[idxE] = (Ptr[idxE] & cmaskE) | orBitsE; }
//beaver beer //c**t cocktails //g-spot spirits //womb wiskey //vaginal vodka //crotch scotch //slit sake //cervix cider //fanny fruitwine //hymen //labia lager //ovarian absinthe //placenta //snatch //uterus tequila void Update() { if (this.isActive && base.isReady) { Ray ray = new Ray(this.transform.position, this.transform.forward); RaycastHit hit; //raycast first if (Physics.Raycast(ray, out hit, this.myRange, Bitwise.Off(1, 8))) { this.myTarget = hit.collider; } else { this.myTarget = null; float closest = float.MaxValue; foreach (var collider in UnityEngine.Object.FindObjectsOfType <Collider>()) { if (Logic <int> .Neither(collider.gameObject.layer, 1, 8)) { float distance = Linear_Algebra.Distance_To_Collider(ray, collider, closest); if (distance < closest) { closest = distance; this.myTarget = collider; } } } } } }
/// <summary> /// Returns all bits in range as ulong. /// </summary> /// <param name="pos">Position in bit array.</param> /// <param name="numBits">Number of bits to get (must be 1-64).</param> /// <returns>Returns requested range of bits.</returns> public ulong GetBits(int pos, int numBits = 1) { CheckArgsUlong(pos, numBits); var idxB = pos >> 6; var shiftB = pos & 0x3f; if (shiftB + numBits <= 64) { var mask = 0xfffffffffffffffful >> (64 - numBits); return(Bitwise.ExtractBits(Ptr[idxB], shiftB, mask)); } var end = math.min(pos + numBits, Length); var idxE = (end - 1) >> 6; var shiftE = end & 0x3f; var maskB = 0xfffffffffffffffful >> shiftB; ulong valueB = Bitwise.ExtractBits(Ptr[idxB], shiftB, maskB); var maskE = 0xfffffffffffffffful >> (64 - shiftE); ulong valueE = Bitwise.ExtractBits(Ptr[idxE], 0, maskE); return((valueE << (64 - shiftB)) | valueB); }
/// <summary> /// Performs a linear search for a consecutive sequence of 0s of a given length in the bit array. /// </summary> /// <param name="pos">Position to start search in bit array.</param> /// <param name="numBits">Number of 0-bits to find.</param> /// <returns>Returns index of first bit of 0-bit range, or int.MaxValue if 0-bit range is not found.</returns> /// <exception cref="ArgumentException"> /// Thrown if: /// - Number of bits is less than 1. /// - Range searched has less than `numBits`. /// - `pos` is not within accepted range [0 - Length]. /// </exception> public int Find(int pos, int numBits) { var count = Length - pos; CheckArgsPosCount(pos, count, numBits); return(Bitwise.Find(Ptr, pos, count, numBits)); }
/// <summary> /// Creates new instance. /// </summary> /// <param name="polynomial">Polynomial value.</param> /// <param name="initialValue">Starting digest.</param> /// <param name="reflectIn">If true, input byte is in reflected (LSB first) bit order.</param> /// <param name="reflectOut">If true, digest is in reflected (LSB first) bit order.</param> /// <param name="finalXorValue">Final XOR value.</param> /// <remarks> /// Name Poly Init RefIn RefOut XorOut /// --------------------------------------------- /// Dallas 0x31 0x00 true true 0x00 /// Maxim 0x31 0x00 true true 0x00 /// /// ATM 0x07 (x^8 + x^2 + x^1 + 1) /// CCITT 0x87 (x^8 + x^7 + x^3 + x^2 + 1) /// 0xD5 (x^8 + x^7 + x^6 + x^4 + x^2 + 1) /// </remarks> public Crc8(byte polynomial, byte initialValue, bool reflectIn, bool reflectOut, byte finalXorValue) { this._currDigest = initialValue; this._reverseIn = !reflectIn; this._reverseOut = !reflectOut; this._finalXorValue = finalXorValue; polynomial = Bitwise.Reverse(polynomial); for (int i = 0; i < 256; i++) { byte crcValue = (byte)i; for (int j = 1; j <= 8; j++) { if ((crcValue & 1) == 1) { crcValue = (byte)((crcValue >> 1) ^ polynomial); } else { crcValue >>= 1; } //if } //for j this._lookup[i] = crcValue; }//for i this._currDigest = initialValue; }
public void UpdateCGB(MMU mmu, int value) { int register = mmu.ReadByte(PaletteIndexAddress); bool increment = Bitwise.IsBitOn(register, 7); int index = register & 0x3F; int colorToModify = (index % 8) / 2; if ((index % 8) % 2 == 0) { red[colorToModify] = value & 0x1F; green[colorToModify] = (green[colorToModify] & 0x18) | (value >> 5); } else { green[colorToModify] = (green[colorToModify] & 0x07) | ((value & 0x03) << 3); blue[colorToModify] = (value >> 2) & 0x1F; } Colors[colorToModify].R = (int)((red[colorToModify] / 31.0) * 255); Colors[colorToModify].G = (int)((green[colorToModify] / 31.0) * 255); Colors[colorToModify].B = (int)((blue[colorToModify] / 31.0) * 255); if (increment) { index = (index + 1) % 64; mmu.WriteByte(index | (0x80), PaletteIndexAddress); } }
protected override void OnInitialise() { List<byte[]> DestSource = Fetch(); // Carry out the subtraction and discard the results(That is how comparison works in assembly, it has the same flags as subtraction). Result = Bitwise.Subtract(DestSource[0], DestSource[1], out _); }
public void TestCreateUIntMask() { var uciStream = new UciStream(); var mask = Bitwise.CreateUIntMask(7, 11); uciStream.WriteMessageLine(Bitwise.ToString(mask)); Assert.That(Bitwise.ToString(mask), Is.EqualTo("00000000_00000000_00001111_10000000")); }
// Removes the token from the types the player has collected private void RemoveToken(TokenTimer tt) { // Clear the appropriate token bit and remove the timer from the list of running timers types = Bitwise.ClearBit(types, (int)tt.TokenType); TokenTimer t = timers.Find(i => i.ID.Equals(tt.TokenType.ToString())); timers.Remove(t); }
public void RemoveArrowType(Enums.Arrows type) { // Clear the appropriate token bit and remove the timer from the list of running timers types = Bitwise.ClearBit(types, (int)type); TokenTimer t = timers.Find(i => i.ID.Equals(type.ToString())); timers.Remove(t); }
protected override void OnInitialise() { // Fetch operands List <byte[]> Operands = Fetch(); // Subtract and store the result flags. Like cmp, only the flags are stored. ResultFlags = Bitwise.Subtract(Operands[1], Operands[0], out _); }
/// <summary> /// Removes all active tokens from the player so shooting an arrow is only the normal arrow /// </summary> public void ClearAllTokens() { foreach (TokenTimer t in timers) { types = Bitwise.ClearBit(types, (int)t.TokenType); Destroy(t); } timers.Clear(); }
public void TestStartPosition() { var uciStream = new UciStream(); var board = uciStream.Board; board.SetPosition(Board.StartPositionFen); uciStream.WriteMessageLine(board.ToString()); // Validate integrity of board and occupancy of every square. board.AssertIntegrity(); Assert.That(board.CurrentPosition.GetPiece(Square.a8), Is.EqualTo(Piece.BlackRook)); Assert.That(board.CurrentPosition.GetPiece(Square.b8), Is.EqualTo(Piece.BlackKnight)); Assert.That(board.CurrentPosition.GetPiece(Square.c8), Is.EqualTo(Piece.BlackBishop)); Assert.That(board.CurrentPosition.GetPiece(Square.d8), Is.EqualTo(Piece.BlackQueen)); Assert.That(board.CurrentPosition.GetPiece(Square.e8), Is.EqualTo(Piece.BlackKing)); Assert.That(board.CurrentPosition.GetPiece(Square.f8), Is.EqualTo(Piece.BlackBishop)); Assert.That(board.CurrentPosition.GetPiece(Square.g8), Is.EqualTo(Piece.BlackKnight)); Assert.That(board.CurrentPosition.GetPiece(Square.h8), Is.EqualTo(Piece.BlackRook)); var square = Square.a7; do { Assert.That(board.CurrentPosition.GetPiece(square), Is.EqualTo(Piece.BlackPawn)); square++; } while (square <= Square.h7); do { Assert.That(board.CurrentPosition.GetPiece(square), Is.EqualTo(Piece.None)); square++; } while (square <= Square.h3); do { Assert.That(board.CurrentPosition.GetPiece(square), Is.EqualTo(Piece.WhitePawn)); square++; } while (square <= Square.h2); Assert.That(board.CurrentPosition.GetPiece(Square.a1), Is.EqualTo(Piece.WhiteRook)); Assert.That(board.CurrentPosition.GetPiece(Square.b1), Is.EqualTo(Piece.WhiteKnight)); Assert.That(board.CurrentPosition.GetPiece(Square.c1), Is.EqualTo(Piece.WhiteBishop)); Assert.That(board.CurrentPosition.GetPiece(Square.d1), Is.EqualTo(Piece.WhiteQueen)); Assert.That(board.CurrentPosition.GetPiece(Square.e1), Is.EqualTo(Piece.WhiteKing)); Assert.That(board.CurrentPosition.GetPiece(Square.f1), Is.EqualTo(Piece.WhiteBishop)); Assert.That(board.CurrentPosition.GetPiece(Square.g1), Is.EqualTo(Piece.WhiteKnight)); Assert.That(board.CurrentPosition.GetPiece(Square.h1), Is.EqualTo(Piece.WhiteRook)); // Validate piece counts. Assert.That(Bitwise.CountSetBits(board.CurrentPosition.WhitePawns), Is.EqualTo(8)); Assert.That(Bitwise.CountSetBits(board.CurrentPosition.WhiteKnights), Is.EqualTo(2)); Assert.That(Bitwise.CountSetBits(board.CurrentPosition.WhiteBishops), Is.EqualTo(2)); Assert.That(Bitwise.CountSetBits(board.CurrentPosition.WhiteRooks), Is.EqualTo(2)); Assert.That(Bitwise.CountSetBits(board.CurrentPosition.WhiteQueens), Is.EqualTo(1)); Assert.That(Bitwise.CountSetBits(board.CurrentPosition.WhiteKing), Is.EqualTo(1)); Assert.That(Bitwise.CountSetBits(board.CurrentPosition.BlackPawns), Is.EqualTo(8)); Assert.That(Bitwise.CountSetBits(board.CurrentPosition.BlackKnights), Is.EqualTo(2)); Assert.That(Bitwise.CountSetBits(board.CurrentPosition.BlackBishops), Is.EqualTo(2)); Assert.That(Bitwise.CountSetBits(board.CurrentPosition.BlackRooks), Is.EqualTo(2)); Assert.That(Bitwise.CountSetBits(board.CurrentPosition.BlackQueens), Is.EqualTo(1)); Assert.That(Bitwise.CountSetBits(board.CurrentPosition.BlackKing), Is.EqualTo(1)); }
private void EncodeBinarySubCode(double absValue, byte[] buffer) { uint pieces = (uint)Math.Min(Math.Floor(absValue / _precisionPiece), (double)_maxPrecisionBitMask); for (int bitIdx = _spikeCodeCfg.ComponentHalfCodeLength - 1, i = 0; bitIdx >= 0; bitIdx--, i++) { buffer[i] = (byte)Bitwise.GetBit(pieces, bitIdx); } return; }
public int CurrentImplementation() { var sum = 0; for (int i = 0; i < _testValues.Length; i++) { sum += Bitwise.NumberOfLeadingZeros(_testValues[i]); } return(sum); }
public override void Execute() { // Calculate the result of incrementation byte[] Result; FlagSet ResultFlags = Bitwise.Increment(Fetch()[0], out Result); // Set the result. Bitwise.Increment() does not set the carry flag. Set(Result); ControlUnit.SetFlags(ResultFlags); }
public override void Execute() { // Perform the decrement byte[] Result; FlagSet ResultFlags = Bitwise.Decrement(Fetch()[0], out Result); // Store results Set(Result); ControlUnit.SetFlags(ResultFlags); }
public void Set(byte[] data) { // The input data must be the size of $size * 2. Otherwise there would be no need for a SplitRegisterHandle. // Set $upper to the upper bytes of $data (Take $size bytes from the end of $data) Upper.Set(Bitwise.Subarray(data, (int)Size)); // Set $lower to the lower $size bytes of $data. Lower.Set(Bitwise.Cut(data, (int)Size)); }
internal static RedisValue Get(Bitwise operation) { switch(operation) { case Bitwise.And: return AND; case Bitwise.Or: return OR; case Bitwise.Xor: return XOR; case Bitwise.Not: return NOT; default: throw new ArgumentOutOfRangeException("operation"); } }