I am very new to C# and using VS, but need a little help.
I have a textbox where a user can put in a value, for example "658". I want to convert this into bytes first (max 3 bytes) before sending it to the serialport. So the first byte sent is 0x02 and the second byte sent is0x92.
The second thing I am having issues with is the same but in reverse. I receive data in bytes, for example "0x0B, 0xC7, 0x14" and then I need to convert them into a decimal value and display them in a different Textbox.
I have tried a number of conversions that did not seem to work (parse, Tobyte and even using binary converter) so I am in need of help.
Thanks
This should get you started:
Convert From Numeric to Bytes:
var textInput = "658";
// validate...
var numericInput = Convert.ToInt32(textInput);
var convertedToBytes = BitConverter.GetBytes(numericInput);
// if your system is little endian (see below), reverse array output.
Convert From Bytes to Numeric:
// fourth octet is required to convert to an int32, which requires 4 bytes.
var bytesInput = new byte[] { 0x0, 0x0B, 0xC7, 0x14 };
// if your system is little endian (see below), reverse array.
var convertedFromBytes = BitConverter.ToInt32(bytesInput, 0);
Note, you want to pay attention to endian-ness. See this: https://msdn.microsoft.com/en-us/library/bb384066.aspx
You can use Encoding.GetBytes and Encoding.GetString to convert string to byte[] and back.
https://msdn.microsoft.com/ru-ru/library/ds4kkd55(v=vs.110).aspx
https://msdn.microsoft.com/ru-ru/library/744y86tc(v=vs.110).aspx
That should no be a problem as both the sending and the receiving serial port will accept/return a byte array. So the question comes down to how you create a by array from a string.
byte[] bytes = Encoding.ASCII.GetBytes(textBox1.Text);
The way back is:
string s = Encoding.ASCII.GetString(bytes);
Related
I am trying to convert byte array to string but bytes are not being converted to string correctly.
byte[] testByte = new byte[]
{
2, 200
};
string string1 = Encoding.ASCII.GetString(testByte);
byte[] byte1 = Encoding.ASCII.GetBytes(string1);
string1 is giving value as \u0002? and byte1 is not getting converted back to 2 and 200. I tried with UTF8 but that is also giving same problem.
I have been given 256 array of chars and integer values. I need to write these values on media as string and read back as bytes. I need conversion to write and read byte data. I am facing problems when integer value comes more then 127.
What should I do so I get original byte values from string?
You appear to be using an encoding backwards. A text Encoding(such as ASCII) is for converting arbitrary text data into encoded (meaning: specially formatted) binary data.
(a caveat should be included here that not all encodings support all text characters; ASCII only supports code-points 0-128, for example, but that isn't the main problem with the code shown)
You appear to want to treat arbitrary binary data as a string - which is the exact opposite. Arbitrary binary data, and encoded text data. Not a problem: just use base-N for some N. Hex (base-16) would work, but base-64 will be more space efficient:
string encoded = Convert.ToBase64String(testByte);
byte[] decoded = Convert.FromBase64String(encoded);
I need to send two INT16 values as 4 bytes via UDP to Unity.
When I use packet sender and send HEX like e.g. "f1 ff 0f 00", Unity translates respective HEX back to INT in Unity as expected.
However, I don't get this to work in C++.
I can send data from my C++ code as follows:
boost::asio::io_service io_service;
udp_send client(io_service, "127.0.0.1", "8052");
client.send("F1FF0F00");
I am also able to create the right HEX format in C++, representing a HEX Integer (%x format). Unfortunately, these HEX formats all came as array of %x which isn't accepted by the boost send method above.
I tried to send various strings to Unity - however, data that Unity receives are not interpreted correctly - hence my conversion doesn't work as needed.
Below is a routine in C# that does what I am looking for. For my purpose, I need something similar in C++:
//empty UDP buffer
byte[] UDP_Data = new byte[8];
//add steering data to buffer
Int16 twobytes = (Int16)(15);
byte[] intBytes = BitConverter.GetBytes(twobytes);
UDP_Data[0] = intBytes[0];
UDP_Data[1] = intBytes[1];
//add speed data to buffer
twobytes = (Int16)(-15);
intBytes = BitConverter.GetBytes(twobytes);
UDP_Data[0] = intBytes[0];
UDP_Data[1] = intBytes[1];
// send via UDP
client.Send(UDP_Data, UDP_Data.Length, ep)
Does anybody know how to rewrite similar code as the above C# in C++ so that data received by Unity are correct?
Any help is highly appreciated.
You are getting confused between text and hex.
This is text "F1FF0F00" not hex.
This is hex
uint8_t udp_data[4] = { 0xF1, 0xFF, 0x0F, 0x00 };
I have a byte array representing a gzipped json array. I send this array in chunks (up to 20 bytes) over a Bluetooth connection to another device. To indicate a start of a new transmission, I send some "reset bytes" (a sequence indicating that we have a new transmission) to the other device. However, for this approach to work, I would need to make sure that the reset bytes are unique in the sense that the gzipped and chunked json array would not contain the same sequence.
The following snipped shows a shortened version of the code I use:
//the sequence I choose as reset sequence
var nullByteSeq = new byte[3] { 0x00, 0x00, 0x00 };
//send the reset sequence to device
var reseted = await characteristic.Write(nullByteSeq);
//messageJson is gzipped json format of a message
var messageJson = BluetoothHelper.GetMessageJson(message);
//header: first 10 bytes: message name - byte 10 to 19: message size
var header = BluetoothHelper.GetMessageHeader(message);
var written = await characteristic.Write(header);
while (bytesSentCounter < messageJson.Count()) {
var toSend = messageJson.Skip(bytesSentCounter).Take(mtu).ToArray();
var sent = await characteristic.Write(toSend);
bytesSentCounter += toSend.Count();
}
As you can see I use three 0x00 bytes as "reset bytes". However, in some cases the messageJson is in such a format, that the last chunk sent has exactly three 0x00 bytes.
Therefore my question: Is there any kind of byte sequence that will never occur at the end of an gzip byte sequence? And if not, how can I achieve what I want?
To answer the original question, no. The end of a gzip stream is the number of uncompressed bytes represented in the last gzip member, modulo 232, in little-endian order. So for long enough inputs, the last four bytes can be anything. The four bytes before that is the CRC-32 of the uncompressed data, so the last eight bytes can be anything. Before that is compressed data, and that can be anything as well for a few thousand bytes.
Thanks to #Name McChange I was able to solve this problem.
As pointed out by him I used base64 encode to remove 0x00 bytes from the gzip bytes array. However instead of base64 encoding the whole byte array, I just encoded the last three bytes of that array. This is sufficient, since the confusion described in the question can only occur when the last three bytes of the gzip array are 0x00 and the array is chunked in such a way, that the last write transmission contains only three bytes.
I post this answer in the hope that it might help someone.
Good morning,
I'm new to network programming but have been doing research and got the basics of setting up a server/client application. I would like to send binary data via TCP from the server to the client to parse and print out integers based on certain field lengths.
I'm basically creating a dummy server to send network data and would like for my client to parse it.
My idea is to create a byte array: byte[] data = {1,0,0,0,1,0,0,1) to represent 8 bytes being set. For example, the client would read the first 2 bytes and print a 2 followed by the next 6 bytes and print a 9.
This is a simple example. The byte array I would like to send would be 864 bytes. I would parse the first 96,48,48 etc.
Would this be a good way of doing this? If not, how should I send 1s and 0s? I found many example sending strings but I would like to send binary data.
Thanks.
You seem to be confusing bits and bytes.
A byte is composed of 8 bits, which can represent integer values from 0 to 255.
So, Instead of sending {1,0,0,0,1,0,0,1}, splitting the byte array and parsing the bytes as bits to get 2 and 9, you could simply create your array as:
byte[] data={2,9};
To send other primitive data types(int,long,float,double...), you can convert them to a byte array.
int x=96;
byte[] data=BitConverter.GetBytes(x);
The byte array can then be written into stream as
stream.Write(data,0,data.Length);
On the client side, parse the byte arrays as:
int x=BitConverter.ToInt32(data,startIndex);
MSDN has great references on TCP clients and listeners.
https://msdn.microsoft.com/en-us/library/system.net.sockets.tcplistener(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient(v=vs.110).aspx
I have a c# library which practically starts listening on a tcpip server an accepts a buffer of a certain size.
I need to send this packet as Byte array from php over the socket in a form of byte array or equivalent.
The packet is constructed for example byte[1] (a flag) is a number from 0 to 255 and byte[6] to byte[11] contains a float number in a string fromat for example:
005.70 which takes 6 bytes representing every character.
I managed to send the flag but when i try to send the float number it does not convert on the other side (C#).
So my question how can i send a byte array to c# using php?
From the C# part the conversion is being handled as follows:
float.Parse(System.Text.Encoding.Default.GetString(Data, 6, 6));
Just after i have posted the question i have dictated my answer. I am not 100% sure if this is the right way but it managed to convert correctly.
Here is the answer:
I created an array of characters and escaped the flag (4) to be the actual byte value being (4) but i didn't escape the money value
$string = array (0=>"\0", 1=>"\4", 2=>"\0", 3=>"\0", 4=>"\0", 5=>"\0", 6=>"5", 7=>".", 8=>"7", 9=>"\0", 10=>"\0");
Imploded all together with nothing as glue:
$arrByte = implode("", $string);
and sent over the opened socket:
$success = #fwrite($this->socket, $arrByte);