LoginSignup
0
1

More than 5 years have passed since last update.

C > ビット演算 > MSBとLSBのみ1とする実装 > return (1u << (size-1)) | 1;

Last updated at Posted at 2015-11-05

MSBとLSBのみ1としたい。
ビット関連のデバッグに使用する。

例として3ビットの場合、101bを得たい。
5ビットの場合、10001bを得たい。

try1(間違いあり)

#include <stdio.h>

unsigned long getOnlyMSBandLSB(int size)
{
    return (1u << (size-1)) + 1;
}

int main(void) 
{
    unsigned long res;

    res = getOnlyMSBandLSB(3);
    printf("0x%X\n", res);

    res = getOnlyMSBandLSB(5);
    printf("0x%X\n", res);
    return 0;
}
結果
0x5
0x11

try2 (修正版)

size==1の時の失敗と訂正方法について @fuzzball さんに教えていただいた。
感謝です。

#include <stdio.h>

unsigned long getOnlyMSBandLSB(int size)
{
    return (1u << (size-1)) | 1;
}

unsigned long oldFunc(int size)
{
    return (1u << (size-1)) + 1; // mistake!!!
}

int main(void) 
{
    unsigned long res;

    res = oldFunc(1);
    printf("0x%X\n", res);

    res = getOnlyMSBandLSB(1);
    printf("0x%X\n", res);

    res = getOnlyMSBandLSB(3);
    printf("0x%X\n", res);

    res = getOnlyMSBandLSB(5);
    printf("0x%X\n", res);
    return 0;
}
結果
0x2
0x1
0x5
0x11

0
1
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
1