Page 1 of 1

[v2] Hex Format Issue (same for v1)

Posted: 07 Aug 2019, 11:01
by xroot
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.

Example

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.

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

Posted: 07 Aug 2019, 11:16
by wolf_II
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.

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

Posted: 07 Aug 2019, 12:14
by jeeswg
- '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

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

Posted: 10 Aug 2019, 02:23
by lexikos
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))
;or
MsgBox Format("{:02.2s}", Format("{:X}", -1))
The "s" can be omitted.