# Developers Planet

sowjanya attaluri February 2016

### How to convert double value to two byte array in c#

I am developing a windows forms application. I have a double value 1.5.That value I need to convert into a two byte array. But when I am converting using BitConverter.GetBytes, getting 8 bytes of data. Please refer my code below.

double d = 1.5;
byte[] array = BitConverter.GetBytes(d);

Amit February 2016

A double is a 64 bit value that just so happens to be 8 bytes. There's nothing that can be done about this.

Gediminas Masaitis February 2016

A double is 8 bytes in length, so unless you want a specific sub-array out of the 8 you're getting (you probably don't), then this is the wrong way to go about it.

You can cast your variable to a single-precision float. That will of course lose some precision, but you will get 4 bytes instead of 8.

If this is still unacceptable, you need to have an implementation of a half-precision float, which sadly doesn't come out-of-the-box with .NET.

I found an implementation here: http://sourceforge.net/p/csharp-half/code/HEAD/tree/System.Half

You can use it like this:

var half = (Half)yourDouble;
var bytes = Half.GetBytes(half); // 2 bytes

Dmitry Bychenko February 2016

Double is 8 byte value, so if you have an arbitrary double there's no hope for you; however, if you have some restrictions, e.g. the value is in the [0..100] range and has at most 2 digits after the decimal point, you can encode it:

// presuming source in [0..100] with at most 2 digit after decimal point
double source = 1.5;

// short is 2 byte value
short encoded = (short) (source * 100 + 0.5);

byte[] array = BitConvertor.GetBytes(encoded);

// decode back to double
double decoded = encoded / 100.0;

#### Post Status

Asked in February 2016
Viewed 2,988 times
Voted 8