EN
C#/.NET - convert int to byte
2 points
In C#/.NET type can be converted to byte in few ways.
xxxxxxxxxx
1
int input = 123;
2
byte output = Convert.ToByte(input);
3
Console.WriteLine(output);
Output:
xxxxxxxxxx
1
123
Note: Convert.ToByte prevents value overflowing (min value 0, max value 255).
xxxxxxxxxx
1
int input = 1234;
2
byte output = (byte)input;
3
Console.WriteLine(output);
Output:
xxxxxxxxxx
1
123
Note: This kind of conversion cuts most significant bits!xxxxxxxxxx
1For conversion int 1234 to byte cutting behaves like in this example:
2______________________________________________________ ___________
3Bit index: 31 23 15 7 0 | | |
4Bit value: 0000 0000 0000 0000 0000 0100 1101 0010 (2)| => | 1234 (10) |
5Bit value: 1101 0010 (2)| => | 210 (10) |