Question

Is there a way to custom format a string for a negative hexadecimal?

I would like a format to show up like -$1,X or $A,X. if a value is 0xff I want it to appear as -$1. The value is a signed value. and I notice that {0:X2} would display it as 'ff' instead of '-1'.

Was it helpful?

Solution

I'm not sure I really understand your question. Lets assume that you are dealing with items of type sbyte (since it is the only type that makes sense in the context). You could create a method like this:

String FormatByte(sbyte b) {
    return (b & 0x80) == 0x80 ? String.Format("-${0}", -b) : String.Format("${0:X}", b);
    }

Which when called with a -59 returns -$59 and when called with 10 returns $A

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top