0

Does not get correct result using this code. After inserting 300 as int, I am getting 44 as the converted byte value.

I was expecting 255 as this is the closest to 300.

Console.Write("Enter int value - ");
val1 = Convert.ToInt32(Console.ReadLine());

// converting int to byte
bval1 =  (byte) val1;
Console.WriteLine("int explicit conversion");
Console.WriteLine("byte - {0}", bval1);
Hamid Pourjam
  • 20,441
  • 9
  • 58
  • 74
Pranay
  • 21
  • 2
  • I have no idea what you're expecting. Since `300` doesn't fit in `byte`, obviously you won't get `300`, but what were you hoping for instead of `44`? –  Jan 01 '16 at 17:12
  • 1
    Why is 255 the expected result? – stuartd Jan 01 '16 at 17:22
  • 1
    It seems you imagine that datatypes have a certain capacity and overflowing them just means that you will be stuck at full capacity? It doesn't work like that... – Martin Smith Jan 01 '16 at 17:29

2 Answers2

6

A single unsigned byte can hold a range of 0 to 255. or 0x00 to 0xff. 300 is greater than 256 so it "wraps around" or begins counting again from 0. 300 - 44 = 256, that's your wrap.

headkase
  • 171
  • 5
6

You have just experienced byte overflow. Try to use types that can actually hold the numbers that you work with.

[edit]

It looks that conversion can be also checked in C#:

bval1 =  checked ((byte) val1);

and have the appropriate exception (OverflowException) when value is too big

Community
  • 1
  • 1
Alexei - check Codidact
  • 22,016
  • 16
  • 145
  • 164