LoginSignup
0

More than 1 year has passed since last update.

C#でint型データのx桁目のbitの状態を取得する

Last updated at Posted at 2022-01-27
    /// <summary>
    /// int型データの指定ビット目が1か0か判定
    /// </summary>
    /// <param name="data">元データ</param>
    /// <param name="digit">判定するビット桁</parma>
    /// <returns>指定データの指定ビットが1の場合はTRUE、0の場合はFALSEを返す</returns>
    bool IsOn(int data, int digit){
        // チェックしたいビットを1桁目に右シフトする
        // (例) 1101 の3桁目をチェックしたい場合、2ビット右シフト 1101 → 0011
        int x = data >> (digit - 1);

        // 1とのAND演算をして1ビット目だけを 1 or 0 の状態にする
        // (例) 0011 & 0001 -> 0001
        int y = x & 1;

        // 結果が1か0かを判定
        bool isOn = y == 1;

        return isOn;
    }

引数のバリデーションなど細かい部分は割愛

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