Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Integer Overflow for UInt32 in Delphi

I use the following function to convert an AnsiString to an Uint32. The AnsiString is is composed of bitsream characters of 0 and 1.

I am using Delphi 12.1

function BinaryStringToUInt32(const binaryStr: AnsiString): UInt32;
var
  i: Integer;
begin
  Result := 0;
  // Convert the binary value to an integer
  for i := 1 to Length(binaryStr) do
  begin
    Result := Result * 2 + Ord(binaryStr[i]) - Ord('0');
  end;
end;

However, I get an Interger overflow for high values close to the uint32 maximum range. How is this possible?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

If I change the code to the following, it works fine:

function BinaryStringToUInt32(const binaryStr: AnsiString): UInt32;
var
  i: Integer;
  test: UInt64;
begin
  test := 0;
  // Convert the binary value to an integer
  for i := 1 to Length(binaryStr) do
  begin
    test := test * 2 + Ord(binaryStr[i]) - Ord('0');
  end;
  Result :=  UInt32(test);
end;

this code is probably more efficient and works as well:

function BinaryStringToUInt32(const binaryStr: AnsiString): UInt32;
var
  i: Integer;
begin
  // Ensure input string length does not exceed 32 characters
  if Length(binaryStr) > 32 then
    raise Exception.Create('Input string exceeds 32 characters');

  Result := 0;
  // Convert the binary value to an integer
  for i := 1 to Length(binaryStr) do
  begin
    Result := Result shl 1; // Shift result left by one bit
    if binaryStr[i] = '1' then
      Result := Result or 1; // Set the least significant bit if current bit is '1'
  end;
end;

>Solution :

Your calculation

Result := Result * 2 + Ord(binaryStr[i]) - Ord('0');

is evaluated from left to right. Therefore it can happen that adding Ord(binaryStr[i]) overflows before Ord('0') is subtracted.

Enclosing Ord(binaryStr[i]) - Ord('0') in brackets should make it work.

Result := Result * 2 + (Ord(binaryStr[i]) - Ord('0'));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading