Following this question I have extracted a byte into a specific bit . Now I have to go back to origin. But couldn't find any suitable solution to back. I have a byte array and it's length is 3. Extracted the array in the following function.
public static void ParserData(byte[] data)
{
int x = data[0] >> 6;
int y = data[0] & 63;
byte[] btMac = data.SubArray(1, 2);
string btmac= BitConverter.ToString(value: btMac, 0);
}
From the above ParserData
function I have extracted x and y from data[0]
and btmac
from data.SubArray(1, 2)
. Now I have to push x and y value to data[0]
and btmac
to data[1,2]
in GenerateData(int x, int y, string btmac)
function so that the both function will be vice-versa.
public static byte[] GenerateData(int x, int y, string btmac)
{
byte[] data = new byte[3];
// code goes here
return data;
}
Getting stack to solve this issue and find no solution. How do I do that?
You should be able to do something like this
var xy = (byte)((x << 6) | y) // combine bits from x and y into a byte, this assumes values are in a valid range
var ms = new MemoryStream();
using( var bw = new BinaryWriter(ms)){
bw.Write(xy); // write the xy byte
bw.Write(btmac[0]); // write the single character in the string
}
var result = ms.ToArray(); // create an array with the result
Note that this is completely untested.
In general I would recommend using a real serialization library rather than messing around with serializing/deserializing binary data yourself. Something like Protobuf.Net should only produce marginally larger data-size, while being much easier to use, and also provide much more compatibility in just about every way.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.