Articles

Use BinToOct function to convert number in binary format to octal format.

function BinToOct(BinStr: string): string;
var
  i: Integer;
  OctPart: Real;
  LastPart, OctStr: string;
  Error: Boolean;
begin
  Error:=False;
  OctStr:='';
  case Length(BinStr) mod 3 of
    1: BinStr:='00'+BinStr;
    2: BinStr:='0'+BinStr;
  end;

  while Length(BinStr)>0 do
  begin
    LastPart:=Copy(BinStr, Length(BinStr)-2, 3);
    Delete(BinStr, Length(BinStr)-2, 3);
    OctPart:=0;
    for i:=1 to 3 do
      if not (LastPart[i] in ['0', '1']) then
      begin
        ShowMessage('This is not binary number');
        Error:=True;
        Break;
      end
      else
        OctPart:=OctPart+StrToInt(LastPart[i])*Power(2, 3-i);
    OctStr:=OctStr+FloatToStr(OctPart);
  end;
  Result:='';
  if Error<>True then
  begin
    for i:=1 to Length(OctStr) do
      Result:=Result+OctStr[Length(OctStr)-i+1];
    while (Result[1]='0') and (Length(Result)>1) do
      Delete(Result, 1, 1);
  end;
end;