How do I convert an int to two bytes in C#?
An int value can be converted into bytes by using the method int. to_bytes().
To convert smaller units to larger units (convert bytes to kilobytes or megabytes) you simply divide the original number by 1,024 for each unit size along the way to the final desired unit.
A single hexadecimal digit (0 - F => 0000 - 1111 ) represents 4 binary bits. Therefore, a 16 bit memory address would require 4 hexadecimal digits, 0000-FFFF. This is commonly referred to as two bytes, or one “word”. A 16 bit memory address would support 64K of memory.
Assuming you just want the low bytes:
byte b0 = (byte)i,
b1 = (byte)(i>>8);
However, since 'int' is 'Int32' that leaves 2 more bytes uncaptured.
Is it an int16?
Int16 i = 7;
byte[] ba = BitConverter.GetBytes(i);
This will only have two bytes in it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With