Forum > Beginners

hexdecimal question

(1/1)

nugax:
Hey guys, hope you are well!
Just a test:
If I wanted to write out a hex value, say the hex for newline/cr, how would I go about it?

write($0a) (or all 4, ($000a) just writes the decimal.

Is it possible to do this? I can read hex values fine. I have searched and didnt really see any functions besides hex2dec which didnt seem to do what I wanted.

Zoran:
In rtl we have two very similar function sets: SysUtils.IntToHex (https://www.freepascal.org/docs-html/current/rtl/sysutils/inttohex.html) and System.HexStr (https://www.freepascal.org/docs-html/current/rtl/system/hexstr.html).

I have never understood why there are both.

There are small differences in usage (The second parameter in IntToHex is the smallest number of digits which the function returns, whereas HexStr returns exactly that number of digits). And IntToHex returns AnsiString, whereas HexStr returns short string (but these are assignment compatible...).

For example:


--- Code: Pascal  [+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i < x.length; i++) { x[i].style.maxHeight='none'; x[i].style.height = Math.min(x[i].clientHeight+15,306)+'px'; x[i].style.resize = "vertical";}};} ---uses SysUtils;// ...writeln(IntToHex($20, 1)); // prints "20"writeln(IntToHex(32, 1)); // also prints "20"

marcov:

--- Quote from: Zoran on April 15, 2022, 04:40:33 pm ---I have never understood why there are both.

--- End quote ---

As you can see from its all shortstring definition, hexstr is from before Delphi compatibility. So inttohex was added for Delphi compat, and so in the end both were retained for compatibility reasons.

Zoran:
I forgot, the most beautiful way is by using helper function (https://www.freepascal.org/docs-html/current/rtl/sysutils/tintegerhelper.tohexstring.html):


--- Quote ---var
  N: Integer;
// ...

  N := $20;
  Writeln(N.ToHexString(1));
  // or directly:
  Writeln(32.tohexString(1));
--- End quote ---

There is also a parameterless overload, but it defaults to SizeOf() * 2 (that is 8 digits for int32, 16 for Int64).
Anyway, try it yourself.



--- Quote from: marcov on April 15, 2022, 04:54:53 pm ---
--- Quote from: Zoran on April 15, 2022, 04:40:33 pm ---I have never understood why there are both.

--- End quote ---

As you can see from its all shortstring definition, hexstr is from before Delphi compatibility. So inttohex was added for Delphi compat, and so in the end both were retained for compatibility reasons.

--- End quote ---

Thanks.

Navigation

[0] Message Index

Go to full version