Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert datatype 'long' to byte array

I have to convert values (double/float in C#) to bytes and need some help..

// Datatype long 4byte -99999999,99 to 99999999,99
// Datatype long 4byte -99999999,9 to 99999999,9
// Datatype short 2byte -999,99 to 999,99
// Datatype short 2byte -999,9 to 999,9

In my "world at home" i would just string it and ASCII.GetBytes().

But now, in this world, we have to make less possible space.
And indeed that '-99999999,99' takes 12 bytes instead of 4! if it's a 'long' datatype.

[EDIT]
Due to some help and answer I attach some results here,

long lng = -9999999999L;
byte[] test = Encoding.ASCII.GetBytes(lng.ToString());  // 11 byte
byte[] test2 = BitConverter.GetBytes(lng);              // 8 byte
byte[] mybyt = BitConverter.GetBytes(lng);              // 8 byte
byte[] bA = BitConverter.GetBytes(lng);                 // 8 byte

There still have to be one detail left to find out. The lng-variabel got 8 byte even if it helds a lower values, i.e. 99951 (I won't include the ToString() sample).

If the value are even "shorter", which means -999,99 -- 999,99 it will only take 2 byte space.
[END EDIT]

like image 592
Independent Avatar asked Aug 26 '11 08:08

Independent


People also ask

Can we convert long to byte?

Java provide ByteBuffer class to do the same.to convert any byte array, first we need to allocate 8 bytes using ByteBuffer's static method allocate, then put byteArray using put method and flip bytebuffer. by calling getLong() method we can get long value of that byte array.

Can we convert long to byte in Java?

Long class has the following methods for converting long type value to other primitive types. byte byteValue() returns the value of this Long as a byte. double doubleValue() returns the value of this Long as a double. float floatValue() returns the value of this Long as a float.

How do you convert bytes to long objects?

The BigInteger class has a longValue() method to convert a byte array to a long value: long value = new BigInteger(bytes). longValue();

How do you convert long to Ulong?

To convert a long to a ulong, simply cast it: long a; ulong b = (ulong)a; C# will NOT throw an exception if it is a negative number.


2 Answers

Have you checked BitConverter

long lng =-9999999999L;
byte[] mybyt = BitConverter.GetBytes(lng);

hope this is what you are looking

like image 105
V4Vendetta Avatar answered Oct 14 '22 21:10

V4Vendetta


Try to do it in this way:

long l = 4554334;

byte[] bA = BitConverter.GetBytes(l);
like image 35
Nakata Avatar answered Oct 14 '22 21:10

Nakata