1

I have a function that converts a double value into the sbyte and returns its hex representation:

string convertToSByte(double num, double factor)
{

    double _Value = num * factor;

    if (_Value > 127)
    {
        _Value = 127;
    }
    else if (_Value < -127)
    {
        _Value = -127;
    }

    return Convert.ToSByte(_Value).ToString("X2");
}

The calculated _Value is supposed to be within the range of [-127 ; 127] if not then these values have to be set as default.

Question: How can these two if conditions and the setting of the default values be simplified?

EDIT:

I tried using the conditional operator ? but actually it is not much simpler (even a little harder to read) and also not really less code

ps. This question serves more of an educational purpose. To find a different way to check for ranges of a variable

Mong Zhu
  • 23,309
  • 10
  • 44
  • 76
  • 2
    Why do you need to simplify? Your code is quite simple, straightforward and easy to understand. – MakePeaceGreatAgain Sep 07 '17 at 08:38
  • @HimBromBeere I guess for the sake of learn to think in different ways. It has more an educational effect. In production code I would always favor this way of writing that I posted – Mong Zhu Sep 07 '17 at 08:40

1 Answers1

5

You could use Min/Max

string convertToSByte(double num, double factor)
{
    var value = Math.Min(127, Math.Max(-127.0, num * factor));
    return Convert.ToSByte(value).ToString("X2");
}
Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357
  • splendid! Thank you very much. I wait a little for other answers to arrive, but your post is the first candidate for accepting as correct answer. – Mong Zhu Sep 07 '17 at 08:37