Read byte array byte by byte using C# - c#

I have a byte array and I want to read this array byte by byte and displayed each byte as integer.
how to do this using C#?

Given that the array is called bytes:
foreach(var b in bytes)
{
Console.WriteLine((int)b);
}
Though, in all fairness, the cast to int is probably unnecessary for display purposes.

Some of the C# code I have been writing communicates via TCP/IP with legacy C++ applications. Some codes use a raw packet format where C/C++ structures are passed back and forward.
Example of what the legacy code could look like:
Best Practice Mapping a byte array to a structure in C#

Related

Sending binary data via (C#)

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

Php Byte Array Packet

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);

In .NET, why does SerialPort.ReadExisting() return a String instead of a byte array?

In the .NET SerialPort class the ReadExisting() method returns a String instead of an array of bytes. This seems like an odd choice considering that RS232 is typically used to move 7 or 8 bit values, which may or may not be printable characters. Is there a reason for this choice?
Currently I end up using System.Text.Encoding.GetBytes(recvd_data) to convert the String to a byte array. Is there a more efficient method?
SerialPort has a Read overload that reads into the specified Byte[].
http://msdn.microsoft.com/en-us/library/ms143549(v=vs.100).aspx
I have used SerialPort extensively and the best way i've found to read a series of bytes is making multiple calls to ReadByte(). Yes, you read one byte at a time but i've found that keeping it simple has avoided problems.
At best, this method will save you from having to do a convert (since you'll read into a byte array).

Use the data in a c# byte array

I have an image, including image header, stored in a c# byte array (byte []).
The header is at the beginning of the byte array.
If I put the header in a struct (as I did in c++) it looks like this:
typedef struct RS_IMAGE_HEADER
{
long HeaderVersion;
long Width;
long Height;
long NumberOfBands;
long ColorDepth;
long ImageType;
long OriginalImageWidth;
long OriginalImageHeight;
long OffsetX;
long OffsetY;
long RESERVED[54];
long Comment[64];
} RS_IMAGE_HEADER;
How can I do it in c#, how can I get and use all the data in the image header (that stored in the beginning of the byte array)?
Thanks
Structs are perfectly fine in C#, so there should be no issue with the struct pretty much exactly as you've written it, though you might need to add permission modifiers such as public. To convert byte arrays to other primitives, there are a very helpful class of methods that include ToInt64() that will help you convert an array of bytes to another built in type (in this case long). To get the specific sequences of array bytes you'll need, check out this question on various techniques for doing array slices in C#.
The easiest way is to create an analog data structure in c#, I won't go into that here as it is almost the same. An example to read out individual the bytes from the array is below.
int headerVersionOffset = ... // defined in spec
byte[] headerVersionBuffer = new byte[sizeof(long)];
Buffer.BlockCopy(imageBytes, headerVersionOffset, headerVersionBuffer, 0, sizeof(long));
//Convert bytes to long, etc.
long headerVersion = BitConverter.ToInt64(headerVersionBuffer, 0);
You would want to adapt this to your data structure and usage, you could also accomplish this using a stream or other custom data structures to automatically handle the data for you.

C# analog for getBytes in java

There is wonderful method which class String has in java called getBytes.
In C# it's also implemented in another class - Encoding, but unfortunately it returns array of unsigned bytes, which is a problem.
How is it possible to get an array of signed bytes in C# from a string?
Just use Encoding.GetBytes but then convert the byte[] to an sbyte[] by using something like Buffer.BlockCopy. However, I'd strongly encourage you to use the unsigned bytes instead - work round whatever problem you're having with them instead of moving to signed bytes, which were frankly a mistake in Java to start with. The reason there's no built-in way of converting a string to a signed byte array is because it's rarely something you really want to be doing.
If you can tell us a bit about why the unsigned bytes are causing you a problem, we may well be able to help you with that instead.

Categories

Resources