challenge 2進数の記述

 コンピューターの原理は2進数だというのに、多くのプログラミング言語で8進数や16進数しか記述できないのは少し変だとは思いませんか?
 そこで、ソース中に2進数を定数として書く方法、またはその代替手段を考えてください。

ある程度の評価基準を示します(できるところまでで構いません)。
・2進数の表示方法は0と1
・桁数は可変長
・コンパイル等の後に最適化等によって定数に変換されることが見込まれる

Cで関数として実装したものを示しておきます。
1
2
3
4
5
int bin(int b1, int b2, int b3, int b4, int b5, int b6, int b7, int b8){
    return b1<<7 | b2 <<6 | b3<<5 | b4<<4 | b5<<3 | b6<<2 | b7<<1 | b8;
}

int byte = bin(0, 1, 1, 0, 1, 0, 0, 1);

Posted feedbacks - Groovy

十分短く書けたと思います。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
def binary(nishinsu) {
    total=0
    n=1
    nishinsu.reverse().toList().each 
     {total = total + it.toInteger()*n; 
            n*=2 }
    println "ans="+total
}

binary('1100')     // 8
binary('01101001') // 105

Index

Feed

Other

Link

Pathtraq

loading...