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 - XSLT

関数 (テンプレート) binaryToInteger です。パラメーター binary に 2進法の文字列を代入して呼び出します。 この関数は binaryToInteger_ という 補助関数 を呼び出します。この補助関数は 左の文字 の 0 / 1 を数値に変えて、その数値 と残りの文字列 を引数にして 再帰します。原理的には桁数に制限はありません。(XSLT の扱える整数の範囲に限定されますが。)

Docutils System Messages

System Message: ERROR/3 (<string>, line 1); backlink

Unknown target name: "binarytointeger".
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<?xml version="1.0" encoding="Shift_JIS" ?>
<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
>

<xsl:template match="/">
  <xsl:call-template name="binaryToInteger">
    <xsl:with-param name="binary" select="01101001" />
  </xsl:call-template>
</xsl:template>

<xsl:template name="binaryToInteger">
  <xsl:param name="binary" />
  <xsl:call-template name="binaryToInteger_">
    <xsl:with-param name="binary" select="$binary" />
    <xsl:with-param name="result" select="0" />
  </xsl:call-template>
</xsl:template>

<xsl:template name="binaryToInteger_">
  <xsl:param name="binary" />
  <xsl:param name="result" />

  <xsl:variable name="head" select="substring ($binary, 1, 1)" />
  <xsl:variable name="result_" select="$result*2 + $head" />

  <xsl:choose>
    <xsl:when test="1 &lt; string-length ($binary)">
      <xsl:variable name="tail" select="substring ($binary, 2)" />
      <xsl:call-template name="binaryToInteger_">
        <xsl:with-param name="binary" select="$tail" />
        <xsl:with-param name="result" select="$result_" />
      </xsl:call-template>
    </xsl:when>

    <xsl:otherwise>
      <xsl:value-of select="$result_" />
    </xsl:otherwise>
  </xsl:choose>
</xsl:template>

</xsl:stylesheet>

Index

Feed

Other

Link

Pathtraq

loading...