Search code examples
ccasting

Convert negative integer to positive integrer using casting


I want the following idea: I have short a = -4; and I have an unsigned short b = (unsigned short)a; When I printf("%hu", b), why doesn't it print 4? How can I convert a negative integer to a positive integer using casting?


Solution

  • short and unsigned short are normally 16 bit integers. So limits are -32768 to 32767 for the signed version (short) and 0 to 65535 for unsigned short. Casting from signed to unsigned just wraps values, so -4 will be casted to 65532.

    This is the way casting to unsigned works in C language.

    If you accept to use additions/substractions, you can do:

    65536l - (unsigned short) a
    

    The operation will use the long type (because of the l suffix) which is required to be at least a 32 bits integer type. That should successfully convert any negative short integer to its absolute value.