0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

10進数と2進数の変換 |Power Query

Posted at

勉強がてら書いてみたので、置いておきます。
コードの通り、変換できる10進数は正の64bitの整数に限定してます。

コード

10進数⇒2進数

fx_10進数から2進数へ
(DecimalNum as number) as text=>
if Int64.From(DecimalNum)<>DecimalNum
   or DecimalNum < 0 then error "変換対象は正の64bit整数に限ります。"
else if DecimalNum =0 then "0"
else
let
    Source = List.Generate(
                ()=>[current =DecimalNum,
                     mod =Number.Mod(current,2)],
                each [current]>0,
                each [current =Number.IntegerDivide([current],2),
                      mod =Number.Mod(current,2)]
             ),
    BinaryNum = List.Accumulate(
                    {each List.Transform(_,(x)=>Number.ToText(x[mod])),
                     List.Reverse,
                     Text.Combine},
                    Source,
                    (x,y)=>y(x)
                ),
    result = BinaryNum
in
    result

2進数から10進数へ

(BinaryNum as text) as number=>
let
    Source = List.Transform(
                Text.ToList(BinaryNum),
                Number.FromText
    ),
    Multipliers = List.Accumulate(
                    //実行する関数:逆順にして、2の累乗数に変換。                    
                    {List.Reverse,
                     each List.Transform(_,(x)=>Number.Power(2,x))},
                    //0から桁数-1までの連番
                    {0..Text.Length(BinaryNum)-1},
                    (x,y)=>y(x)
    ),
    zipped = List.Zip({Source,Multipliers}),
    calculation = List.Sum(
                    List.Transform(zipped,each _{0}*_{1})
    ),
    //0と1だけなら、空リストになる。
    IsBinaryNum = List.Select(Source,each not List.Contains({1,0},_)) ={},
    result = if IsBinaryNum then calculation
             else error "2進数の表記に誤りがあります。"
in
    result

実行例

0から16の連番に列追加で実行してみました。
10進数から2進数
image.png
さらに2進数から10進数
image.png

おまけ

Power Queryの関数にビット演算はあります。これはExcelのワークシート関数と同じく、10進数で行えます。
Number関数―バイト| Microsoft Docs

0
2
0

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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?