Top community members
All Wiki Articles Create Wiki Article

Welcome to Dirask IT community! ❤ 💻
We are community of people that helps each other.

If you think you have some skills to help others

help someone and become a part of our community - List Q & A

C#/.NET - convert int to byte

0 contributions
2 points

In C#/.NET type can be converted to byte in few ways.

1. Convert.ToByte example

int input = 123;
byte output = Convert.ToByte(input);
Console.WriteLine(output);

Output:

123
Note: Convert.ToByte prevents value overflowing (min value 0, max value 255).

2. Explicit conversion

int input = 1234;
byte output = (byte)input;
Console.WriteLine(output);

Output:

123
Note: This kind of conversion cuts most significant bits!
For conversion int 1234 to byte cutting behaves like in this example:
______________________________________________________      ___________
Bit index: 31        23        15        7       0    |    |           |
Bit value: 0000 0000 0000 0000 0000 0100 1101 0010 (2)| ‬=> | 1234 (10) |
Bit value:    ‭                           1101 0010‬ (2)| => | 210  (10) |

3. References

  1. https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/types/casting-and-type-conversions
0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more