Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert an int to two bytes in C#?

Tags:

c#

int

byte

How do I convert an int to two bytes in C#?

like image 606
xarzu Avatar asked Oct 12 '10 23:10

xarzu


People also ask

How do you convert int to bytes?

An int value can be converted into bytes by using the method int. to_bytes().

How do you divide 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.

What is the hex value stored for for 2 byte integer?

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.


2 Answers

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.

like image 189
Marc Gravell Avatar answered Sep 20 '22 22:09

Marc Gravell


Is it an int16?

Int16 i = 7;
byte[] ba = BitConverter.GetBytes(i);

This will only have two bytes in it.

like image 45
Abe Miessler Avatar answered Sep 17 '22 22:09

Abe Miessler