0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

ビット演算 基本中の基本のビットフラグ操作

Last updated at Posted at 2021-09-12

ビット演算の基本のフラグの上げ下げと指定したビットを操作する関数です。templateクラスです

#include <iostream>


#define BYTE_BIT (8)	//区切り

template<typename T>
class Bit
{

public:

	//コンストラクタ
	Bit()
	{
		bit = 0;
	}
	

	//ビット表示
	void Print()
	{
		for(int i = sizeof(bit) * 8 -1; i >= 0; i--)
		{
			std::cout<< ((bit >> i) & 1) <<" ";

			//区切り
			if( (i % BYTE_BIT) == 0)
			{

				std::cout<<"  ";
			}
		}

		std::cout<<std::endl;
		
	}

	//フラグが立っているかどうか?
	bool IsFlagUp(T number)
	{
		if( (bit >> number) & (T)1)
		{
			return true;
		}
		else
		{
			return false;
		}
	}

	//符号ビットを立たせる
	void SignedUp()
	{	
		bit = bit | ((T)1 << (sizeof(T) * 8 -1));
	}


	//フラグを立たせる 左から何番目か?
	void FlagUp(T  number)
	{
	    if(IsFlagUp(number) == false)
	    {
			number = (sizeof(T) * 8 - 1) - number;
			bit =  bit | (1 << number);
	    }
	}

	//フラグを下げる 左から何番目か?
	void FlagDown(T number)
	{
	    if(IsFlagUp_Int(bit,number) == true)
	    {
			number = (sizeof(T) * 8) - number;
			bit =  bit ^ (1 << number);
	    }
	}

	//フラグをクリア 全部下げる
	void FlagAllDown()
	{

		bit = 0;

		return bit;
	}

	//フラグを全部上げる 
	void FlagAllUp()
	{
		FlagAllDown();	//フラグを下げる
		bit = ~bit;		//ビットを全部反転
	}


	//デストラクタ
	~Bit()
	{
		
	}


private:

	T bit;	//ビット操作対象

};

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?