C# Short Error: Negating the minimum value of a twos complement number is invalid

后端 未结 4 626
小蘑菇
小蘑菇 2020-12-11 00:58

I have been encountering this error for my project, which involves working with Digital Audio Signals.

So I have been getting the amplitude values and recently encou

相关标签:
4条回答
  • 2020-12-11 01:31

    The absolute value of -32768 is +32768... but that's outside the range of short... hence the error. (You're lucky you're seeing this as an exception... other ways of encountering this oddity can give silent overflow, leading to some very odd results)

    Options:

    • Special-case this value, e.g. convert to -32767 first, if the exact value doesn't matter too much
    • Convert it to an int before calling Math.Abs
    0 讨论(0)
  • 2020-12-11 01:34

    What value would you have it be? there is no 32768 in short - only 32767.

    You could write your own method, of course:

    public static short LossyAbs(short value)
    {
        if(value >= 0) return value;
        if(value == short.MinValue) return short.MaxValue;
        return -value;
    }
    

    but this is lossy in that it sort-of loses a value. Perhaps a better idea is: don't use short.MinValue if you intend to (potentially) negate it. Limiting yourself to -32767 would make this go away.

    0 讨论(0)
  • 2020-12-11 01:41

    16 bit signed int (short) takes values between -32,768 and 32,767.

    Negating -32768, or getting the absolute value, is impossible to do inside a 16 bit signed integer. The value (32,768) is greater than the maximum possible positive value (32,767).

    I would not like to advise you how to solve the problem without knowing more details of the algorithms you are using.

    0 讨论(0)
  • 2020-12-11 01:47

    Convert short[] array to int[] array.

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