[v2] Hex Format Issue (same for v1)

Get help with using AutoHotkey and its commands and hotkeys
Posts: 15
Joined: 21 Jun 2019, 08:45

[v2] Hex Format Issue (same for v1)

07 Aug 2019, 11:01

Size or Width in Formatting negative numbers to Hex not working.
Anyone know why?
What am I doing wrong?
I only want 2 chars. with Format ":02X" Hex but returns 16 chars..
I have to use "SubStr" to get 2 chars..
I know 255 will return 2 chars. FF.


Code: Select all

Hex       := Format("{:02X}",-1)
HexLength := StrLen(Hex)
HexSubStr := SubStr(Hex,-2)

MsgBox Format("-1 Hex = {:s}`nHex Length = {:i}`nSubStr = {:s}",Hex,HexLength,HexSubStr)
Thank for any help.
Posts: 2688
Joined: 08 Feb 2015, 20:55

Re: [v2] Hex Format Issue (same for v1)

07 Aug 2019, 11:16

Try this: (to see what :020X does ; it does padding with zeroes)

Code: Select all

Hex       := Format("{:020X}",-1)
HexLength := StrLen(Hex)
HexSubStr := SubStr(Hex,-1)

MsgBox % Format("-1 Hex = {}`nHex Length = {}`nHexSubStr = {}"
                        , Hex,      HexLength,      HexSubStr)
Hex is a 16digit HexValue. Padding it with zeroes will not truncate anything.
I hope that helps.
User avatar
Posts: 6902
Joined: 19 Dec 2016, 01:58
Location: UK

Re: [v2] Hex Format Issue (same for v1)

07 Aug 2019, 12:14

- '02X' and '02' will give a *minimum* of 2 digits.
- Workarounds are using & or Mod.
- SubStr is another possibility, using a negative StartPos, e.g. -1 (AHK v1: last 2 chars), e.g. -2 (AHK v2, more intuitive: last 2 chars). Cheers.

Code: Select all

MsgBox, % Format("{:02X}", 0xABCDEF) ;ABCDEF
MsgBox, % Format("{:02X}", 0xABCDEF & 0xFF) ;EF

MsgBox, % Format("{:02}", 123456) ;123456
MsgBox, % Format("{:02}", Mod(123456, 100)) ;56
homepage | tutorials | wish list | fun threads | donate
WARNING: copy your posts/messages before hitting Submit as you may lose them due to CAPTCHA
Posts: 7085
Joined: 30 Sep 2013, 04:07
GitHub: Lexikos

Re: [v2] Hex Format Issue (same for v1)

10 Aug 2019, 02:23

For the floating-point number and string types, ".Precision" controls the maximum number of characters or decimal places, but unfortunately for integers it only controls the minimum width, apparently the same as "Width" with the 0 prefix. This behaviour comes directly from printf, though in retrospect it would have been better to define our own behaviour (specify maximum characters).

You can do it with multiple Format calls:

Code: Select all

MsgBox Format("{:.2s}", Format("{:02X}", -1))
MsgBox Format("{:02.2s}", Format("{:X}", -1))
The "s" can be omitted.

Return to “Ask For Help”

Who is online

Users browsing this forum: DavidP, Google [Bot], hasantr, Peaceful, Rohwedder, RubbeH, songdg, tatagi and 48 guests