I want to transmit one APDU and I get back the response. I want to check the last two bytes by an API which will log the comparison.
byte[] response = Transmit(apdu);
//response here comes will be 0x00 0x01 0x02 0x03 0x04
//response.Length will be 5
byte[] expectedResponse = { 0x03, 0x04 };
int index = (response.Length)-2;
Log.CheckLastTwoBytes(response[index],expectedResponse);
//The declaration of CheckLastTwoBytes is
//public static void CheckLastTwoBytes(byte[] Response, byte[] ExpResp)
This is an error of invalid arguments. How can I pass the last 2 bytes to APIs?
Use Array.Copy
byte[] newArray = new byte[2];
Array.Copy(response, response.Length-2, newArray, 2);
Log.CheckLastTwoBytes(newArray,expectedResponse);
new ArraySegment<byte>(response, response.Length - 2, 2).Array
EDIT: nevermind this, apparently .Array just returns the original entire array and not the slice. You would have to modify your other method to accept ArraySegment instead of byte[]
Since the type of response[index] is byte (not byte[]), it's not surprising that you'd get that error.
If Log.CheckLastTwoBytes really does check just the last two bytes of its Response parameter, then you should just pass response:
Log.CheckLastTwoBytes(response, expectedResponse)
You can't have a subarray just like that, no...
First solution, obvious one:
var tmp = new byte[] { response[response.Length - 2],
response[response.Length - 1] };
Log.CheckLastTwoBytes(tmp, expectedResponse);
Or, you could do this:
response[0] = response[response.Length - 2];
response[1] = response[response.Length - 1];
Log.CheckLastTwoBytes(response, expectedResponse);
It might be that this function doesn't check for exact lengths, etc, so you could just put the last two bytes as the first two, if you don't care about destroying the data.
Or, alternatively, you can use linq:
byte[] lastTwoBytes = response.Skip(response.Length-2).Take(2).ToArray();
Related
I'm trying to upload an image, and an getting the following exception on the third line:
var file = Request.Files[0];
var imgBytes = new Byte[file.ContentLength - 1];
file.InputStream.Read(imgBytes, 0, file.ContentLength);
var base64String = Convert.ToBase64String(imgBytes,0,imgBytes.Length);
p.Photo = base64String;
Your code says: allocate (n - 1) bytes, read n bytes.
var imgBytes = new Byte[file.ContentLength]; // <- Remove - 1
file.InputStream.Read(imgBytes, 0, file.ContentLength);
Seems you're making a simple mistake when creating your array, and it's probably rooted in the fact that arrays are zero-based (i.e. positions start with 0).
First, to make this extremely clear, consider an array that should contain three elements, {A, B, C}. When you store those in an array, A will have the index 0, B will have 1, and C will be at 2.
In other words, the last item will be at the position length - 1. The length itself though, will still be 3.
Apply that to your situation, and you'll realize the problem lies here:
var imgBytes = new Byte[file.ContentLength - 1];
Remove the -1 and it should work.
If you needed to read directly from the last byte in your array on the other hand, you'd use file.ContentLength - 1 to access it.
I've got a BinaryReader reading in a number of bytes into an array. The underlying Stream for the reader is a BufferedStream(whose underlying stream is a network stream). I noticed that sometimes the reader.Read(arr, 0, len) method is returning different(wrong) results than reader.ReadBytes(len).
Basically my setup code looks like this:
var httpClient = new HttpClient();
var reader = new BinaryReader(new BufferedStream(await httpClient.GetStreamAsync(url).ConfigureAwait(false)));
Later on down the line, I'm reading a byte array from the reader. I can confirm the sz variable is the same for both scenarios.
int sz = ReadSize(reader); //sz of the array to read
if (bytes == null || bytes.Length <= sz)
{
bytes = new byte[sz];
}
//reader.Read will return different results than reader.ReadBytes sometimes
//everything else is the same up until this point
//var tempBytes = reader.ReadBytes(sz); <- this will return right results
reader.Read(bytes, 0, sz); // <- this will not return the right results sometimes
It seems like the reader.Read method is reading further into the stream than it needs to or something, because the rest of the parsing will break after this happens. Obviously I could stick with reader.ReadBytes, but I want to reuse the byte array to go easy on the GC here.
Would there ever be any reason that this would happen? Is a setting wrong or something?
Make sure you clear out bytes array before calling this function because Read(bytes, 0, len) does NOT clear given byte array, so some previous bytes may conflict with new one. I also had this problem long ago in one of my parsers. just set all elements to zero, or make sure that you are only reading (parsing) up to given len
I want to pass the following byte array through serial port.
array[j].abc = 2;
array[j].def = 4;
array[j].gh = 6;
array[j].ij = 0;
array[j].jl = 1;
array[j].fg= 1;
array[j].bh = 2;
I passed the byte array as follow
byte[] wtbin = TestSerializer.StructureToByteArray(array[j]);
byte[] bharr = new byte[1];
bharr[0] = wtbin[i];
serialPort1.Write(bharr, 0, 1);
But serialport receives it as letters like B,B etc. How can
I receive it as numbers??
You can pass a whole byte array (generally named buffer) into the serialPort.Write() method. What you are doing instead is passing a single byte to the method. In your case the call to the method would be something like:
serialport1.Write(wtbin, 0, wtbin.Length);
You can read more about SerialPort on MSDN - SerialPort Write. Additionally keep in mind that you are sending bytes, not ASCII text. Depending on what you are sending PUTTY may display different things. In order to convert a byte array(buffer) back to ASCII, you can use
Encoding.ASCII.GetString(buffer);
Hope this helps :)
I want to receive bytes into an array from tcp client. I've an array of bytes dataToRecieve, in which I'm receiving those bytes.
But I've got some problems here, can anyone check my code:
while (true) {
try {
Socket handler = mainSocket.Accept();
byte[] dataToRecieve = new byte[handler.ReceiveBufferSize];
int[] dataArray = new int[1024];
handler.Receive(dataToRecieve);
//////SOME CODE
int i = handler.Send(msg);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
catch(Exception) {}
--------//////some code
Now I want to receive bytes into byte array & than convert it into the int array (however the data should be in an int array)........
Well, your code already has a problem here:
handler.Receive(dataToRecieve);
You're ignoring the value returned by Receive, to tell you how many bytes were actually read. That's almost always a bad idea. Likewise you're assuming you receive all the information you need in a single call. Usually you'd either have to loop until you'd read all the data - either by knowing that you expect a certain amount, or by reading until there is no more data.
Once you've got the data into a byte array, converting it into an integer array depends on the format in the byte array. You may be able to just use Buffer.BlockCopy, but that's only if the endianness in the byte array matches the endianness in memory. Alternatively, you can simply create an array of the right size, and write a loop:
int[] integers = new byte[size / 4];
for (int i = 0; i < integers.Length; i++)
{
integers[i] = BitConverter.ToInt32(bytes, i * 4);
}
However, again you need to consider the endianness. My MiscUtil library has an EndianBitConverter class which allows you to specify the endianness of your data.
Is there some equivalent to the StringBuilder.Insert method for use with byte arrays? I was going to try and use a MemoryStream but an error was thrown telling me that the MemoryStream object is "not expandable". I need to place bytes within specific spots of another (already existing byte array).
Here is the same idea using StringBuilder.
String firstString = "FirstData";
String someString = "string Data";
int Index = 0;
StringBuilder sb = new StringBuilder(firstString);
for(int i = 0; i < someString.Length; i++)
{
sb.Insert(index, someString[i]);
index += 2;
}
Thank you for any help,
Evan
Use a List; which will allow you to insert as needed. If you have an existing array you can call ToList().
List<byte> data1 = new List<byte>() {10, 11, 12};
List<byte> data2 = new List<byte>() {13, 14, 15};
int Index = 0;
for(int i = 0; i < data1.Count; i++)
{
data2.Insert(index, data2[i]);
index += 2;
}
Then to go back to an array simply call ToArray().
You could use a list of bytes as opposed to an array of byte and use the insert method there.
Have you tried using List, it has an Insert method
A "Stream" by definition flows only one way. There is no way to change something once it's flowed out the gate. If you want this ability, you'll have to create a regular in-memory collection of some kind to give yourself a buffer you can modify before attempting to push the data out to a stream.
You can create a byte array, instead of creating some collection of bytes:
System.Text.ASCIIEncoding encoding=new System.Text.ASCIIEncoding();
Byte[] bytes = encoding.GetBytes("yourString");
or:
byte[] utf8 = System.Text.Encoding.UTF8.GetBytes ("yourString");
Use ASCII or UTF8 or any other conversation.