Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting to byte in C# [duplicate]

Tags:

c#

casting

byte

Possible Duplicate:
What happens when you cast from short to byte in C#?

Can someone explain what's happening when casting a value to a byte, if it's outside the range of min/max byte? It seems to be taking the integer value and modulo it with 255. I'm trying to understand the reason for why this doesn't throw an exception.

int i = 5000;
byte b = (byte)i;

Console.WriteLine(b);  // outputs 136
like image 935
Stealth Rabbi Avatar asked Sep 24 '12 21:09

Stealth Rabbi


1 Answers

5000 is represented as 4 bytes (int) (hexadecimal)

|00|00|13|88|

Now, when you convert it to byte, it just takes the last 1-byte.

Reason: At the IL level, conv.u1 operator will be used which will truncate the high order bits if overflow occurs converting int to byte. (See remarks section in the conv.u1 documentation).

|88|

which is 136 in decimal representation

like image 118
prashanth Avatar answered Oct 06 '22 07:10

prashanth