TSMH’s blog

多趣味人間のメモ

2 進数の文字列を 16 進数の文字列に変換

2 進数の文字列を 16 進数の文字列に変換
サンプルソースをメモ

function BinToHex(SBin : String): String;

Function TFMain.BinToHex(SBin : String): String;
const
    LBit64_1 : UInt64 = 1;
var
    LIndex : Integer; //カウンター
    LBitLen : Integer; //二進数文字列の長さ
    LShiftBits : Int64; //シフト用

    LInt64 : Int64; //最後の値
begin
    LShiftBits := 0;
    LBitLen := 0;

    LInt64 := 0;

    LBitLen := Length(SBin); //入れた値の長さを取得

    for LIndex := 0 to (LBitLen-1) do
    begin
      if SBin[LBitLen- LIndex] = '1' then
      begin
        LInt64 := LInt64 + (LBit64_1 shl LShiftBits);
      end
      else if SBin[LBitLen- LIndex] = '0' then
      begin
        LInt64 := LInt64;
      end;
      LShiftBits := LShiftBits +1;
    end;
    Result := IntToHex(LInt64, 2);

end;

例:
Edit1.Text := BinToHex('11111111');
Edit1.Text ➡ FF

参考文献:
[ 980_数値の 2 進数表示と 16 進数表示 ] - Mr.XRAY