名前空間
変種
操作

stdc_leading_zeros

From cppreference.com
< c‎ | numeric
ヘッダー <stdbit.h> で定義されています。
unsigned int stdc_leading_zeros_uc( unsigned char value ) [[unsequenced]];
(1) (C23以降)
unsigned int stdc_leading_zeros_us( unsigned short value ) [[unsequenced]];
(2) (C23以降)
unsigned int stdc_leading_zeros_ui( unsigned int value ) [[unsequenced]];
(3) (C23以降)
unsigned int stdc_leading_zeros_ul( unsigned long int value ) [[unsequenced]];
(4) (C23以降)
unsigned int stdc_leading_zeros_ull( unsigned long long int value ) [[unsequenced]];
(5) (C23以降)
#define stdc_leading_zeros( value )

// 公開インターフェース

generic_return_type stdc_leading_zeros( generic_value_type value ) [[unsequenced]];
(6) (C23以降)
1-5) 最上位ビットから始まる、連続する 0 ビットの数を返します。
6) 型汎用関数(generic_value_type 引数でマークされている)は、入力値の型に基づいて適切な値を返します。ただし、それは次のいずれかである必要があります。
  • 標準の符号なし整数型(bool を除く)。
  • 拡張符号なし整数型。
  • または、標準または拡張整数型(bool を除く)の幅に一致する、ビット精度の符号なし整数型。
generic_return_type は、計算された結果を表現できる適切な大きな符号なし整数型である必要があります。

目次

[編集] パラメータ

value - 符号なし整数型の値

[編集] 戻り値

最上位ビットから始まる、連続する 0 ビットの数。

[編集]

#include <limits.h>
#include <stdbit.h>
#include <stdint.h>
#include <stdio.h>
 
#define bits_num(value) (sizeof(value) * CHAR_BIT)
 
#define bin_impl(T, suffix) \
const char* bin_##suffix(T x) \
{ \
    static char buf[bits_num(x) * CHAR_BIT + 1]; \
    for (T i = 0, mask = ((T)1 << (bits_num(x) - 1)); mask; mask >>= 1) \
        buf[i++] = x & mask ? '1' : '0'; \
    buf[bits_num(x)] = '\0'; \
    return buf; \
}
 
bin_impl(uint8_t, u8)
bin_impl(uint16_t, u16)
bin_impl(uint32_t, u32)
bin_impl(uint64_t, u64)
 
#define bin(x) _Generic((x), \
    uint8_t: bin_u8, uint16_t: bin_u16, uint32_t: bin_u32, default: bin_u64)(x)
 
int main()
{
    puts("uint8_t:");
    for (uint8_t x = 0b11000000; ; x >>= 1)
    {
        printf("x = [%s], leading zeros: %d\n", bin(x), stdc_leading_zeros(x));
        if (!x)
            break;
    }
 
    puts("uint16_t:");
    for (uint16_t x = 0b11000000; ; x >>= 1)
    {
        printf("x = [%s], leading zeros: %d\n", bin(x), stdc_leading_zeros(x));
        if (!x)
            break;
    }
}

出力

uint8_t:
x = [11000000], leading zeros: 0
x = [01100000], leading zeros: 1
x = [00110000], leading zeros: 2
x = [00011000], leading zeros: 3
x = [00001100], leading zeros: 4
x = [00000110], leading zeros: 5
x = [00000011], leading zeros: 6
x = [00000001], leading zeros: 7
x = [00000000], leading zeros: 8
uint16_t:
x = [0000000011000000], leading zeros: 8
x = [0000000001100000], leading zeros: 9
x = [0000000000110000], leading zeros: 10
x = [0000000000011000], leading zeros: 11
x = [0000000000001100], leading zeros: 12
x = [0000000000000110], leading zeros: 13
x = [0000000000000011], leading zeros: 14
x = [0000000000000001], leading zeros: 15
x = [0000000000000000], leading zeros: 16

[編集] 関連項目

最上位ビットから始まる 0 ビットの最初の位置を見つけます
(型汎用関数マクロ)[編集]
符号なし整数内の 0 ビットの数を数えます
(型汎用関数マクロ)[編集]
最上位ビットから始まる連続する 1 ビットの数を数えます
(型汎用関数マクロ)[編集]
C++ ドキュメント for countl_zero
English 日本語 中文(简体) 中文(繁體)