Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert object to byte array in c#

Tags:

c#

bytearray

I want to convert object value to byte array in c#.

EX:

 step 1. Input : 2200
 step 2. After converting Byte : 0898
 step 3. take first byte(08)

 Output: 08

thanks

like image 262
CRK Avatar asked Nov 15 '10 14:11

CRK


People also ask

How do you convert an object into a byte?

Write the contents of the object to the output stream using the writeObject() method of the ObjectOutputStream class. Flush the contents to the stream using the flush() method. Finally, convert the contents of the ByteArrayOutputStream to a byte array using the toByteArray() method.

Can we convert string to byte array in C#?

The Encoding. GetBytes() method converts a string into a bytes array. The example below converts a string into a byte array in Ascii format and prints the converted bytes to the console.

How do I turn a string into a byte array?

There are two ways to convert byte array to String: By using String class constructor. By using UTF-8 encoding.

How can I get byte array from image?

Read the image using the read() method of the ImageIO class. Create a ByteArrayOutputStream object. Write the image to the ByteArrayOutputStream object created above using the write() method of the ImageIO class. Finally convert the contents of the ByteArrayOutputStream to a byte array using the toByteArray() method.


2 Answers

You may take a look at the GetBytes method:

int i = 2200;
byte[] bytes = BitConverter.GetBytes(i);
Console.WriteLine(bytes[0].ToString("x"));
Console.WriteLine(bytes[1].ToString("x"));

Also make sure you have taken endianness into consideration in your definition of first byte.

like image 196
Darin Dimitrov Avatar answered Sep 22 '22 00:09

Darin Dimitrov


byte[] bytes = BitConverter.GetBytes(2200);
Console.WriteLine(bytes[0]);
like image 27
Aaron McIver Avatar answered Sep 18 '22 00:09

Aaron McIver