2

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.

SLR
  • 45
  • 3
  • 1
    `var x = short.Parse(results)`? – Charlieface Mar 01 '21 at 23:00
  • so I have done this operation. a short is 2 byte. I need to be able to split that and save in 2 bytes of data and those bytes are not together. they are apart. so by splitting I can save the data in those 2 Byte slots – SLR Mar 01 '21 at 23:02
  • 1
    ... followed by `var b1 = (byte)(x & 0xFF); var b2 = (byte)(x >> 8);` – Charlieface Mar 01 '21 at 23:08
  • 1
    Does this answer your question? [Good way to convert between short and bytes?](https://stackoverflow.com/questions/1442583/good-way-to-convert-between-short-and-bytes) – Charlieface Mar 01 '21 at 23:09
  • Is your number decimal or hex? – tymtam Mar 01 '21 at 23:13

2 Answers2

2

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.

Dharman
  • 30,962
  • 25
  • 85
  • 135
TheBlueOne
  • 486
  • 5
  • 13
1

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
tymtam
  • 31,798
  • 8
  • 86
  • 126