ビット構成を表示する

明解C言語 入門編 > 7. 基本型 >

ビット構成を表示する

C


#include <stdio.h>

int count_bits(unsigned x)
{
int count = 0;
while (x)
{
if (x & 1u) count++;
x >>= 1;
}
return count;
}

int int_bits(void)
{
return count_bits(~0u);
}

void print_bits(unsigned x)
{
int i;
for (i = int_bits() - 1; i >= 0; i--)
putchar(((x >> i) & 1u) ? '1' : '0');

putchar('\n');
}

int main(int argc, char* argv[])
{
unsigned x = 10000;
print_bits(x);

return 0;
}

実行結果


R:\>lesson055\project1.exe
00000000000000000010011100010000

Delphi


program Project1;

{$APPTYPE CONSOLE}

uses
SysUtils;

var
x:Longword;

function count_bits(x:Longword):Integer;
var
count:Integer;
begin
count := 0;
while (x <> 0) do
begin
if x and 1 <> 0 then inc(count);
x := x shr 1;
end;
result := count;
end;

function int_bits():Integer;
begin
result := count_bits(Longword(not 0));
end;

procedure print_bits(x:Longword);
var
i: Integer;
begin
for i := int_bits() - 1 downto 0 do
begin
if x shr i and 1 <> 0 then
write('1')
else
write('0');
end;

writeln('');
end;

begin
x := 10000;
print_bits(x);
end.

実行結果


S:\>lesson055\project1.exe
00000000000000000010011100010000

Perl
sub count_bits
{
    my ($x) = @_;
    $count = 0;
    while ($x)
    {
        $count++ if ($x & 1) ;
        $x >>= 1;
    }
    return $count;
}

sub int_bits
{
    return &count_bits(~0);
}

sub print_bits
{
    my ($x) = @_;
    for ($i = &int_bits - 1; $i >= 0; $i--)
    {
        print ((($x >> $i) & 1) ? '1' : '0');
    }

    print "\n";
}

$x = 10000;
&print_bits($x);

実行結果

L:\>perl lesson_07_055.pl
00000000000000000010011100010000

Ruby
def count_bits(x)
    count = 0
    while (x != 0)
        count += 1 if (x & 1 != 0) 
        x = (x >> 1) & ~(~0 << (x.size * 8))
    end
    return count
end

def int_bits
    return count_bits(~0)
end

def print_bits(x)
    (int_bits - 1).downto(0) do |i|
        print(((x >> i) & 1) != 0 ? '1' : '0')
    end

    puts ""
end

x = 10000
print_bits(x)

実行結果

L:\>ruby l:\lesson_07_055.rb
000000000000000000010011100010000