Yes the curious thing is that it seems to work fine inside the ShortInt range (-128..127)
The rule is simple: if the resultant number
after changing the endianess represents a
negative number then the implicit conversion is going to change it by adding extra $FF as much as needed for the nearest available type (2 bytes for Integer in this case).
Your example:
SmallInt 127 is $007F
a- (change endianess) -> $7F00 (which is *not* a negative number)
b- (implicit conversion to integer) -> $00007F00 (because it is not a negative number)
c- IntToHex gives the expected result "7F00"
When the result of changing endianess is a negative number, then we would have to add $FFFF to convert it from SmallInt to Integer and IntToHex would show that!
Another way to handle this is by doing the conversion to Integer by yourself before calling IntToHex. Instead of:
BEStr := IntToHex(NtoBE(TheSmallInt), Dgt);
do:
TheInteger := NtoBE(TheSmallInt) and $0000FFFF;
BEStr := IntToHex(TheInteger, Dgt);
This way when TheSmallInt is $XXYY then after changing its endianess it becomes $YYXX and
TheInteger := NtoBE(TheSmallInt) and $0000FFFF; would yield $0000YYXX
OR
Use unsigned types like WORD instead of SmallInt.