how to print signed hex in c

前端 未结 3 2003
醉酒成梦
醉酒成梦 2020-12-18 19:46

I know we can use printf(\"%04X\", value); to print unsigned hex values

is there a similar flag or a function in c that you can use to print signed hex values?

相关标签:
3条回答
  • 2020-12-18 19:56

    Unfortunately C's printf function has no way to do this directly. You could of course instead try:

    printf("%s%x\n", x<0?"-":"", x<0?-(unsigned)x:x);
    

    Edit: I believe I fixed the issue of handling INT_MIN...

    0 讨论(0)
  • 2020-12-18 20:11

    No, but you can do something like

    printf("%c%04X",(x<0)?'-':' ',(x<0)?-x:x);
    

    But, as other point out, it is doubtful whether there is a valid reason to do so. Be sure to understand exactly what it is that you're asking for.

    EDIT: according to the edit to your post, you do understand what you're asking for, so it's all your fault ;-)

    0 讨论(0)
  • 2020-12-18 20:18

    What do you mean by a "signed" hexadecimal value? Do you want something like "-e0"? If so, what would that mean? The sign is already represented in the hexadecimal display, since it shows all the bits and that's all the information that's in the number.

    0 讨论(0)
提交回复
热议问题