예제 #1
0
std::vector<std::bitset<ROUND_KEY_SIZE> > generate_round_keys(const std::bitset<KEY_SIZE>& key) {
	std::vector<std::bitset<ROUND_KEY_SIZE> > round_keys;
	// split key into lower and upper half, of 28b
	std::bitset<KEY_SIZE/2> lower;
	std::bitset<KEY_SIZE/2> upper;
	int mid = key.size() / 2;
	for (int i = 0; i < key.size(); i++)
		if (i < mid) lower.set(i, key.test(i));
		else upper.set(i % mid, key.test(i));

	for (int i = 0; i < ROUND_NUM; ++i) {
		// left shift using key_schedule
		lower = (lower << key_schedule[i]);
		upper = (upper << key_schedule[i]);
		// permute using pc_2 table
		
		//combine 28b lower and 28b upper for 56b key
		std::bitset<KEY_SIZE> input_key;
		for (i = 0; i < input_key.size(); ++i) {
			if (i < mid) input_key.set(i, lower.test(i));
			else input_key.set(i, upper.test(i % mid));
		}
		
		// permute using pc_2 table
		std::bitset<ROUND_KEY_SIZE> round_key;
		for (int i = 0; i < pc_2.size(); ++i)
			round_key.set(i, input_key[pc_2[i]]);

		round_keys.push_back(round_key);
	}
	
	return round_keys;
}
예제 #2
0
// given plain text and key, return cipher text
std::bitset<BLOCK_SIZE> encrypt(const std::bitset<BLOCK_SIZE>& input_text, const std::bitset<INPUT_KEY_SIZE>& input_key, bool encrypt) {
	std::bitset<BLOCK_SIZE> cipher_block;	
	// generate initial key	
	std::bitset<KEY_SIZE> initial_key = generate_initial_key(input_key);
	
	// generate round keys
	std::vector<std::bitset<ROUND_KEY_SIZE> > round_keys = generate_round_keys(initial_key);
	
	// split input text into two blocks of 32b
	std::bitset<BLOCK_SIZE/2> lower; // use lower to represent bits [0,BLOCK_SIZE/2), and
	std::bitset<BLOCK_SIZE/2> upper; // user upper to represent bits [BLOCK_SIZE/2,BLOCK_SIZE)
	int mid = input_text.size() / 2;
	for (int i = 0; i < input_text.size(); i++)
		if (i < mid) lower.set(i, input_text.test(i));
		else upper.set(i % mid, input_text.test(i));
	
	std::bitset<BLOCK_SIZE/2> temp; // temporarily hold lower, so that upper can be used in XOR
	
	// if encryption
	if (encrypt) {
		for (int i = 0; i < ROUND_NUM; ++i) {
			//std::cout << "ROUND " << i << "----------------------------------------" << std::endl;
			//std::cout << "Using key " <<  i << ":\t\t" << round_keys[i] << std::endl;
			temp = copy_bit_pattern(lower); // hold r_i-1 in temp
			lower = perform_round(lower, round_keys[i]);
			lower ^= upper; // r_i = f(r_i-1,key) xor l_i-1
			upper = copy_bit_pattern(temp); // l_i = r_i-1
			std::cout << "ROUND " << i << " ENDED" << "----------------------------------" << std::endl;
		}
	} else {
		// if decryption
		for (int i = ROUND_NUM -1; i >= 0; --i) {
			//std::cout << "ROUND " << i << "----------------------------------------" << std::endl;
			//std::cout << "Using key " <<  i << ":\t\t" << round_keys[i] << std::endl;
			temp = copy_bit_pattern(lower); // hold r_i-1 in temp
			lower = perform_round(lower, round_keys[i]);
			lower ^= upper; // r_i = f(r_i-1,key) xor l_i-1
			upper = copy_bit_pattern(temp); // l_i = r_i-1
			//std::cout << "ROUND " << i << " ENDED" << "----------------------------------" << std::endl;
		}
	}
	
	// perform final swap
	for (int i = 0; i < cipher_block.size(); ++i) {
		if (i < mid) cipher_block.set(i, upper.test(i));
		else cipher_block.set(i, lower.test(i % mid));
	}
	
	return cipher_block;
}
예제 #3
0
void Sync::choose_threads(){
    int ref = -1;
    for (UINT ii=0; ii<num_threads; ii++){
        unsigned int i = (ii + rrcounter) % num_threads;
        if ( !t[i].ignore && !was_executed.test(i) ){
            ref = i;
            break;
        }
    }
    if (ref == -1){
        was_executed.reset();
        for (UINT ii=0; ii<num_threads; ii++){
            unsigned int i = (ii + rrcounter) % num_threads;
            if (!t[i].ignore){
                ref = i;
                break;
            }
        }
    }
    
    for (UINT i=0; i<num_threads; i++){
        t[i].is_active = !t[i].ignore && t[i].pc == t[ref].pc;
        if (t[i].is_active){
            was_executed.set(i);
        }
    }
    
    // Next
    rrcounter = (ref + 1) % num_threads;
}
예제 #4
0
std::bitset<KEY_SIZE> generate_initial_key(const std::bitset<INPUT_KEY_SIZE>& input_key) {
	// permute using pc_1 table, and return output
	std::bitset<KEY_SIZE> output_key;
	for (int i = 0; i < pc_1.size(); ++i) {
		output_key.set(i, input_key.test(pc_1[i] - 1));
	}
	return output_key;
}
예제 #5
0
void expect_eq_set(
    std::string label,
    std::bitset<BITS> bset,
    quadset<BITS> quad
) {
  for (bitpos i = 0; i < BITS; ++i) {
    EXPECT_EQ((bset.test(i)?1000:0)+i, (quad.test(i)?1000:0)+i) << label;
  }
}
예제 #6
0
std::bitset<32> perform_sbox_subst(const std::bitset<48>& input) {
    std::bitset<32> output;
    for (int i = 0; i < NUM_S_BOXES; ++i) {
        int row = 0;
        int col = 0;
        //row bits are in bits 0,5
        if (input.test(6*i)) row += 1;
        if (input.test(6*i+5)) row += 2;
        
        //column bits are bits[1,5)
        if (input.test(6*i+1)) col += 1;
        if (input.test(6*i+2)) col += 2;
        if (input.test(6*i+3)) col += 4;
        if (input.test(6*i+4)) col += 8;
        
	// perform substitution for block i using s-box i
        std::bitset<4> sbox_out = s_boxes[i][row][col];
        for (int j = 0; j < 4; ++j) output.set(i*4+j,sbox_out.test(j));
    }
    return output;
}
예제 #7
0
int eNFA::is_status_cinal(std::bitset<100> state)
{
	int status = 0;

	for ( int s=0; s < 100; ++s )
	{
		if ( state.test(s) )
			status |= _table[s].first;
	}

	return status;
}
예제 #8
0
파일: op_killer.hpp 프로젝트: alibaba/tair
bool OPKiller::do_test(const base_packet *p) {
    //~ Test namespace first.
    int area = p->ns();
    if (!areas_filter_.test(area & BLOOM_FILTER_MASK)) {
        return true;
    }
    if (target_areas_.find(area) == target_opcodes_.end()) {
        return true;
    }

    int opcode = p->getPCode();
    if (!opcodes_filter_.test(opcode & BLOOM_FILTER_MASK)) {
        return true;
    }
    if (target_opcodes_.find(opcode) == target_opcodes_.end()) {
        return true;
    }

    log_info("op[%d] of area[%d] refused.", opcode, area);
    return false;
}
예제 #9
0
bool AxString::IsBitset(std::bitset<256> &filter)
{
   if (IsEmpty()) 
      return false;

   for (char *cpos = (char *) m_pByteArray; *cpos; cpos++) {
      if (false == filter.test((unsigned char)(*cpos & 0xff))) {
         return false;
      }
   }

   return true;
}
예제 #10
0
파일: poj1753.cpp 프로젝트: jflyup/POJ
int flip()
{
	int loop_count = 0;

	while(!stat_queue.empty())
	{
		loop_count++;
		unsigned long stat = stat_queue.front();
		stat_queue.pop();
		if(finished(stat))
		{
			int steps = 0;
			while(path[stat] != 0)
			{
				++steps;
				stat = path[stat];
			}
			printf("%d", steps);
			return 0;
		}
		int xPos, yPos;
		for(xPos = 0; xPos < N; ++xPos)
		{
			for(yPos = 0; yPos < N; ++yPos)
			{
				int i;
				std::bitset < 16 > next_stat(stat);
				for(i = 0; i < 5; ++i)
				{
					if(is_legal_position(xPos + move[i][0], yPos + move[i][1]) )
					{
						next_stat.flip((xPos + move[i][0]) * N + (yPos + move[i][1]) );
					}

				}

				//printf("%d\n", next_stat.to_ulong());
				unsigned long num_status = next_stat.to_ulong();
				if(!status_set.test(num_status))
				{
					status_set.set(num_status);
					//remember where current status comes from.
					path[num_status] = stat;
					stat_queue.push(num_status);
				}
			}
		}
	}
	printf("Impossible");
	return -1;
}
예제 #11
0
파일: optimize.cpp 프로젝트: 2bj/hhvm
void insert_assertions_step(const php::Func& func,
                            const Bytecode& bcode,
                            const State& state,
                            std::bitset<kMaxTrackedLocals> mayReadLocalSet,
                            bool lastStackOutputObvious,
                            Gen gen) {
  for (size_t i = 0; i < state.locals.size(); ++i) {
    if (options.FilterAssertions) {
      if (i < mayReadLocalSet.size() && !mayReadLocalSet.test(i)) {
        continue;
      }
    }
    auto const realT = state.locals[i];
    auto const op = makeAssert<bc::AssertObjL,bc::AssertTL>(
      borrow(func.locals[i]), realT
    );
    if (op) gen(*op);
  }

  if (!options.InsertStackAssertions) return;

  // Skip asserting the top of the stack if it just came immediately
  // out of an 'obvious' instruction.  (See hasObviousStackOutput.)
  assert(state.stack.size() >= bcode.numPop());
  auto i = size_t{0};
  auto stackIdx = state.stack.size() - 1;
  if (lastStackOutputObvious) {
    ++i, --stackIdx;
  }

  /*
   * This doesn't need to account for ActRecs on the fpiStack, because
   * no instruction in an FPI region can ever consume a stack value
   * from above the pre-live ActRec.
   */
  for (; i < bcode.numPop(); ++i, --stackIdx) {
    auto const realT = state.stack[stackIdx];

    if (options.FilterAssertions &&
        !realT.strictSubtypeOf(stack_flav(realT))) {
      continue;
    }

    auto const op = makeAssert<bc::AssertObjStk,bc::AssertTStk>(
      static_cast<int32_t>(i), realT
    );
    if (op) gen(*op);
  }
}
예제 #12
0
void NavFramer::Subframe::load(const std::bitset<5 * 300>& bs)
{
   bitset<30> word;
   for (int w=0; w<10; w++)
   {
      for(int b=0; b<30; b++)
         word[29-b] = bs.test((ni + w*30 + b)%1500);
      
      if (inverted)
         word = ~word;

      words[w] = word.to_ulong();
   }
   complete = true;
}
예제 #13
0
bool File::Open(std::string aFileName, std::bitset<8> aSetOfFlags)
{
	if(myFile != NULL)
	{
		return false;
	}
	std::string flags;
	if(aSetOfFlags.test(READ))
	{
		if(aSetOfFlags.test(WRITE))
		{
			flags += "r+";
		}
		else
		{
			flags += "r";
		}
	}
	else
	{
		if(aSetOfFlags.test(WRITE))
		{
			if(aSetOfFlags.test(APPEND))
			{
				flags += "a+";
			}
			else
			{
				flags += "w";
			}
		}
		else
		{
			assert(aSetOfFlags.test(APPEND));
			flags += "a";
		}
	}
	if(aSetOfFlags.test(BINARY))
	{
		flags += "b";
	}
	myFile = fopen(aFileName.c_str(), flags.c_str());
	myFlags = aSetOfFlags;

	if(myFile == NULL)
	{
		return false;
	}

	fseek(myFile , 0 , SEEK_END);
	mySize = ftell (myFile);
	rewind (myFile);

	return true;
}
예제 #14
0
	void OnUserConnect(LocalUser* user)
	{
		ConfigTag* tag = user->MyClass->config;
		std::string vhost = tag->getString("vhost");
		std::string replace;

		if (vhost.empty())
			return;

		replace = "$ident";
		if (vhost.find(replace) != std::string::npos)
		{
			std::string ident = user->ident;
			if (ident[0] == '~')
				ident.erase(0, 1);

			SearchAndReplace(vhost, replace, ident);
		}

		replace = "$account";
		if (vhost.find(replace) != std::string::npos)
		{
			std::string account = GetAccount(user);
			if (account.empty())
				account = "unidentified";

			SearchAndReplace(vhost, replace, account);
		}

		if (vhost.length() > 64)
		{
			ServerInstance->Logs->Log("m_conn_vhost", DEFAULT, "m_conn_vhost: vhost in connect block %s is too long", user->MyClass->name.c_str());
			return;
		}

		/* from m_sethost: validate the characters */
		for (std::string::const_iterator x = vhost.begin(); x != vhost.end(); x++)
		{
			if (!hostmap.test(static_cast<unsigned char>(*x)))
			{
				ServerInstance->Logs->Log("m_conn_vhost", DEFAULT, "m_conn_vhost: vhost in connect block %s has invalid characters", user->MyClass->name.c_str());
				return;
			}
		}

		user->ChangeDisplayedHost(vhost.c_str());
	}
예제 #15
0
std::bitset<BLOCK_SIZE/2> perform_round(const std::bitset<BLOCK_SIZE/2>& data, const std::bitset<ROUND_KEY_SIZE>& round_key) {
	// expand/permute data from 32b to 48b using e_table
	std::bitset<48> expansion;
	for (int i = 0; i < e_table.size(); ++i) {
		expansion.set(i, data.test(e_table[i] - 1));
	}
	expansion ^= round_key;

	// perform s-box substitution on expanded data	
	std::bitset<32> s_box_out = perform_sbox_subst(expansion);
	
	// permute using P table
	std::bitset<32> shrinkage;
	for (int i = 0; i < p_table.size(); ++i)
		shrinkage.set(i, expansion.test(p_table[i] - 1));
	return shrinkage;
}
예제 #16
0
파일: appears.cpp 프로젝트: agentzh/appears
/* search_missing_combinations: traverse the BitTable
 * to find 0 bits and print out the corresponding
 * character sequences */
void
search_missing_combinations () {
    unsigned long missing_combs = 0;
    char buf[APPEARS_SEQSIZE + 1];
    for (unsigned long i = 0; i < TABLESIZE; i++) {
        if (!BitTable.test(i)) {
            index_to_tokens(i, buf);
            printf("  %s (index %lu)\n", buf, i);
            missing_combs++;
        }
    }
    if (missing_combs) {
        printf("For total %lu missing combinations found.\n",
                missing_combs);
    } else {
        printf("All combinations have appeared.\n");
    }
}
예제 #17
0
파일: p357.cpp 프로젝트: sagi/contests
int main()
{
    generate_sieve();

    long long result = 0;
    for (auto prime : primes) {
        int n = prime - 1;
        bool valid = true;
        for (int d=1; d*d<=n && valid; ++d) {
            if (n%d == 0) {
                valid &= sieve.test(d + n / d);
            }
        }
        if (valid) {
            result += n;
        }
    }

    std::cout << result << std::endl;
    return 0;
}
예제 #18
0
파일: main.cpp 프로젝트: maanuel/metnum-tp2
std::pair<Matrix, std::vector<Label>> filterDataset(const Matrix &A, const std::vector<Label> &labels, const std::bitset<K> &filter) {
    Timer timer("Filter Dataset Timer");

    if (K < labels.size() || filter.count() <= 1) {
        std::stringstream fmt;
        fmt << "Filtro para el dataset tiene tamaño " << K << " cuando el dataset tiene tamaño " << labels.size();
        throw new std::invalid_argument(fmt.str());
    }

    std::vector<Label> output(filter.count(), 0.0);
    int last = 0;

    for (int i = 0; i < A.rows(); ++i) {
        if (filter.test((std::size_t) i)) {
            output[last] = labels[i];
            last++;
        }
    }

    return std::pair<Matrix, std::vector<Label>>(Matrix(A, filter), output);
}
  void NullDerefProtectionTransformer::instrumentCallInst(llvm::Instruction*
    TheCall, const std::bitset<32>& ArgIndexs) {
    llvm::CallSite CS = TheCall;

    for (int index = 0; index < 32; ++index) {
      if (!ArgIndexs.test(index)) continue;
      llvm::Value* Arg = CS.getArgument(index);
      if (!Arg) continue;
      llvm::Type* ArgTy = Arg->getType();

      llvm::BasicBlock* OldBB = TheCall->getParent();
      llvm::ICmpInst* Cmp
        = new llvm::ICmpInst(TheCall, llvm::CmpInst::ICMP_EQ, Arg,
                             llvm::Constant::getNullValue(ArgTy), "");

      llvm::Instruction* Inst = Builder->GetInsertPoint();
      llvm::BasicBlock* NewBB = OldBB->splitBasicBlock(Inst);

      OldBB->getTerminator()->eraseFromParent();
      llvm::BranchInst::Create(getTrapBB(NewBB), NewBB, Cmp, OldBB);
    }
  }
예제 #20
0
 void printFlags(std::ostream &out, std::bitset<N> const &flags) {
     std::size_t count = flags.count();
     if (count == 0) {
         out << "none";
     } else {
         std::size_t j = 0;
         for (std::size_t i = 0; i < N; ++i) {
             if (flags.test(i)) {
                 if (count == 2 && j == count - 1) {
                     out << " and ";
                 } else if (count >= 3 && j >= 1 && j < count - 1) {
                     out << ", ";
                 } else if (count >= 3 && j == count - 1) {
                     // Serial comma.
                     out << ", and ";
                 }
                 out << T(i);
                 ++j;
             }
         }
     }
 }
예제 #21
0
void expect_op_result(
    std::string op,
    std::bitset<BITS> bits,
    quadset<BITS> q1,
    quadset<BITS> q2,
    quadset<BITS> quad,
    speed_tradeoff tradeoff = ACCURATE
) {
  for (bitpos i = 0; i < BITS; ++i) {
    if (bits.test(i) != quad.test(i)) {
      EXPECT_EQ(false, true) << q1.to_string() << ' ' << op << ' '
        << q2.to_string() << " = " << quad.to_string()
        << "; expected " << bits;
    }
  }
  if (tradeoff != FAST) {
    if ((BITS & 0x3F) != 0) {
      for (bitpos i = BITS; i < ((BITS+63) & ~0x3F); ++i) {
        EXPECT_EQ(false, quad.test(i)) << "found set bit (#"
          << i << ") out of set range in " << quad.to_string() << op;
      }
    }
  }
}
예제 #22
0
파일: dce.cpp 프로젝트: KOgames/hhvm
void remove_unused_locals(Context const ctx,
                          std::bitset<kMaxTrackedLocals> usedLocals) {
  if (!options.RemoveUnusedLocals) return;
  auto const func = ctx.func;

  /*
   * Removing unused locals in closures requires checking which ones
   * are captured variables so we can remove the relevant properties,
   * and then we'd have to mutate the CreateCl callsite, so we don't
   * bother for now.
   *
   * Note: many closure bodies have unused $this local, because of
   * some emitter quirk, so this might be worthwhile.
   */
  if (func->isClosureBody) return;

  func->locals.erase(
    std::remove_if(
      begin(func->locals) + func->params.size(),
      end(func->locals),
      [&] (const std::unique_ptr<php::Local>& l) {
        if (l->id < kMaxTrackedLocals && !usedLocals.test(l->id)) {
          FTRACE(2, "  removing: {}\n", local_string(borrow(l)));
          return true;
        }
        return false;
      }
    ),
    end(func->locals)
  );

  // Fixup local ids, in case we removed any.
  for (auto i = uint32_t{0}; i < func->locals.size(); ++i) {
    func->locals[i]->id = i;
  }
}
std::map<UserID, wns::CandI>
AllPossibleGroupsGrouper::getCandIs(std::vector<UserID> allUsers,
                                    std::bitset<MAX_STATIONS> bitset, ModeType mode)
{
    std::map<UserID, wns::CandI> candis;
    candis.clear();

    unsigned int noOfStations = allUsers.size();

    switch(mode)
    {
        case tx:
        {
            if (beamforming)
            {

                std::map<wns::node::Interface*, wns::Power> userNoiseIInterMap;
                userNoiseIInterMap.clear();

                for (unsigned int k = 0; k < noOfStations; ++k)
                if (bitset.test(k))
                {
                    userNoiseIInterMap[allUsers[k].getNode()] = 
                    colleagues.registry->estimateTxSINRAt(allUsers[k]).interference;
                }
            candis = convertMap(friends.ofdmaProvider->calculateCandIsTx(userNoiseIInterMap, x_friendliness, txPower));
            }   
            else
            { 
                // no beamforming
                assure(noOfStations == 1, "We don't do beamforming, so only one-user groups are supported");
                UserID user = allUsers[0];
                wns::scheduler::ChannelQualityOnOneSubChannel cqi = 
                colleagues.registry->estimateTxSINRAt(user);
                candis[user] = wns::CandI(cqi.carrier, cqi.interference);
            }

            break;
        }
        case rx:
        {
            if (beamforming)
            {
                std::vector<wns::node::Interface*> combination;
                combination.clear();

                for (unsigned int k = 0; k < noOfStations; ++k)
                if (bitset.test(k))
                {
                    combination.push_back(allUsers[k].getNode());
                }
                candis = convertMap(friends.ofdmaProvider->calculateCandIsRx(combination,
                colleagues.registry->estimateRxSINROf(allUsers[0]).interference));
                //use estimated interference of user 0 for all other
                //terminals as well, maybe average over all entries?
                //see TreeBasedGrouper
            }
            else
            {
            // no beamforming
            assure(noOfStations == 1, "We don't do beamforming, so only one-user groups are supported");
            UserID user = allUsers[0];
            wns::scheduler::ChannelQualityOnOneSubChannel cqi = 
            colleagues.registry->estimateRxSINROf(user);
            candis[user] = wns::CandI(cqi.carrier, cqi.interference);
            }

            break;
        }
        default:
            assure(0, "Wrong mode, can  either be RX or TX");
    }
    return candis;
}
예제 #24
0
	inline bool is_alt() const { return modifiers.test( alt); } // option on Mac keyboard
bool set(std::bitset<N>& bset, uint32 pos) {
    bool old = bset.test(pos);
    bset.set(pos);
    return old;
}
예제 #26
0
bool getDebugFlag(DebugFlags _flag) {

    return g_flags.test(_flag);

}
예제 #27
0
 bool TestAvailableState(EKnockBackAnimationState s) const { return x80_availableStates.test(size_t(s)); }
예제 #28
0
	inline bool is_command() const { return modifiers.test( command); }
예제 #29
0
	bool checkFlag (T f) const
	{
		return FLAG.test (f);
	}
예제 #30
0
	bool checkFlag(T f, Args ... rest) const
	{
		if (sizeof ...(rest))
			return FLAG.test(f) && checkFlag (rest...);
		return FLAG.test (f);
	}