SLR
SLR

Reputation: 45

Split and store an integer into two byte

I am working on a Embedded systems and I have only 2 Bytes of storage. I need to store a JSON response in those 2 byte. the JSON response is a string containing 2 digits. How can I convert the string to an unsigned integer split and save into those 2 bytes. I am using C#:

var results = "16";

I need to convert this and store it into 2 bytes.

Upvotes: 2

Views: 1177

Answers (2)

tmaj
tmaj

Reputation: 35017

What @TheBlueOne said - a two digit number, even when hexadecimal requires just 1 byte - but for larger numbers you can use BitConverter.GetBytes.

var s2 = "FF01"; 
var n = Convert.ToUInt16(s2, 16); 
var bytes = BitConverter.GetBytes(n);
//bytes[0] = 1
//bytes[1] = 255

Upvotes: 1

TheBlueOne
TheBlueOne

Reputation: 496

As your value is only 2 digits long you just need 1 byte to store it. You can just call Byte.Parse("16") and you will get 16 as a byte. You can then store your byte whereever you want.

Upvotes: 2

Related Questions