Home > database >  String of bits To Hex value
String of bits To Hex value

Time:09-27

I have a string like '10011011001', And I wish to convert this string into Hex string, what is the best way to do that.

CodePudding user response:

The OP clarified that the input string's length is <= 32. Then the problem becomes simpler.

There are many possible solutions. One of them is this:

function BinStrToHex32(const S: string): string;
begin
  var LValue: UInt32 := 0;
  for var i := 1 to S.Length do
    case S[i] of
      '0', '1':
        LValue := LValue shl 1 or Ord(S[i] = '1');
    else
      raise Exception.CreateFmt('Invalid binary number: %s', [S]);
    end;
  Result := IntToHex(LValue);
end;

which IMHO is quite readable and performs some validation. (For bonus points, you can add overflow checking.)

If there were no restriction to the input string length, then I'd do something like this:

function BinStrToHexStr(const S: string): string;
const
  HexDigits: array[0..$F] of Char = '0123456789ABCDEF';
begin

  if S.Length mod 8 <> 0 then
    raise Exception.Create('Invalid binary string.');

  SetLength(Result, S.Length div 4);

  var LNibble: Byte := 0;
  var c := 0;
  for var i := 1 to S.Length do
  begin
    LNibble := LNibble shl 1 or Ord(S[i] = '1');
    if i mod 4 = 0 then
    begin
      Inc(c);
      Result[c] := HexDigits[LNibble];
      LNibble := 0;
    end;
  end;

end;
  • Related