LoginSignup
0
1

More than 5 years have passed since last update.

C > bit演算 > 指定のビット数まで1で埋めた数値の取得 | link:printf()での二進数表記

Last updated at Posted at 2017-07-26
動作環境
C

仕様

ある数値を与えたとき、その数値のビット数まで1で埋めた値を得ること。

例:
2 -> 0b11
4 -> 0b1111

実装

やっていることは「(ビット数+1)の値から1引く」だけ。

#include <stdio.h>

#define DISP_BITS (20)

// modified from 
// https://stackoverflow.com/questions/111928/is-there-a-printf-converter-to-print-in-binary-format
void print_binary(int number, int num_digits) {
    int digit;
    int cnt = 0;
    for(digit = num_digits - 1; digit >= 0; digit--) {
        if (cnt % 4 == 0) {
            printf(" ");
        }
        printf("%c", number & (1 << digit) ? '1' : '0');
        cnt++;
    }
}

//
int getBitFilled(int bitnum)
{
    bitnum--;
    return ((2<<bitnum)-1);
}

void Test_getBitFilled(int val)
{
    if (val < 1 || val > DISP_BITS) {
        return; // error
    }
    int bitFilled = getBitFilled(val);
    printf("%3d -", val);
    print_binary(bitFilled, DISP_BITS);
    printf("\n");
}

int main(void) {
    Test_getBitFilled(3);
    Test_getBitFilled(1);
    Test_getBitFilled(4);
    Test_getBitFilled(1);
    Test_getBitFilled(5);
    Test_getBitFilled(20);

    return 0;
}
run
  3 - 0000 0000 0000 0000 0111
  1 - 0000 0000 0000 0000 0001
  4 - 0000 0000 0000 0000 1111
  1 - 0000 0000 0000 0000 0001
  5 - 0000 0000 0000 0001 1111
 20 - 1111 1111 1111 1111 1111

関連して学んだこと

printf()での二進数表記

printf()では2進数表記の書式指定子がないということを今さら知りました。

https://stackoverflow.com/questions/111928/is-there-a-printf-converter-to-print-in-binary-format
のKresimirさんの回答を参考にしました。

v0.2

@fujitanozomu さんのコメントにてgetBitFilled()の訂正をしていただきました。

@shiracamus さんのコメントにてprint_binary()の空白位置の改善とputchar()使用での方法を教えていただきました。

ともに情報感謝です。

#include <stdio.h>

#define DISP_BITS (20)

void print_binary(int number, int num_digits) {
    int digit;
    for(digit = num_digits - 1; digit >= 0; digit--) {
        putchar(number & (1 << digit) ? '1' : '0');
        if (digit > 0 && digit % 4 == 0)
            putchar(' ');
    }
}

//
int getBitFilled(int bitnum)
{
    return ((1<<bitnum)-1);
}

void Test_getBitFilled(int val)
{
    if (val < 1 || val > DISP_BITS) {
        return; // error
    }
    int bitFilled = getBitFilled(val);
    printf("%3d -", val);
    print_binary(bitFilled, DISP_BITS);
    printf("\n");
}

int main(void) {
    Test_getBitFilled(3);
    Test_getBitFilled(1);
    Test_getBitFilled(4);
    Test_getBitFilled(1);
    Test_getBitFilled(5);
    Test_getBitFilled(20);

    return 0;
}

run
  3 -0000 0000 0000 0000 0111
  1 -0000 0000 0000 0000 0001
  4 -0000 0000 0000 0000 1111
  1 -0000 0000 0000 0000 0001
  5 -0000 0000 0000 0001 1111
 20 -1111 1111 1111 1111 1111
0
1
3

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
1