Search code examples
integerhexpascalnumber-manipulation

Manipulating hexadecimal numbers in Pascal


I'm currently reading up on binary and hexadecimal number manipulation and I'm finding it difficult to complete a task and was wondering if anyone can help clarify this question for me.

I have a hexadecimal number '04831037' and I need to replace the first number (0) with a '1' via a Pascal program. I'm not sure how to go about doing this.

I know how to convert an integer into a hexadecimal value via:

var 
  iNumber : Integer;

begin
  iNumber := 75698231;
  writeln(IntToHex(iNumber, 8));
end.

> Output: 04831037

But now I am confused on how to replace a single number in the output. Any help would be greatly appreciated


Solution

  • Hexadecimal numbers are of base 16, i.e. each digit represents a value 0..15.

    To form a value of ex. 16, i.e. $10 following expression could be used: (Note: the $ sign means that the value is a hexadecimal value)

    16 = $10 = 1*161 + 0*160

    The value 28 ($1C) is expressed by:

    28 = $1C = 1*161 + 12*160

    To add $10000000 to a number, use

    $10000000 = 1*167

    In code that would look like:

    iNumber := iNumber + $10000000; 
    

    Lets look at the question:

    I have a hexadecimal number '04831037' and I need to replace the first number (0) with a '1'

    This means you will first subtract the number with $00000000 and then add $10000000.

    In code that would be:

    iNumber := $04831037;
    iNumber := iNumber - $00000000 + $10000000;
    WriteLn(IntToHex(iNumber,8)); // Writes '14831037'