Right now, I'm creating a reader for a file.
When I do the split with Encoding.Unicode, the result just returns the original string for some reason.
Here's the code:
string thefile = File.ReadAllText("file.bin", Encoding.Unicode); // also does the same if I do GetString() and ReadAllBytes
byte[] delim = { 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00 };
string delims = Encoding.Unicode.GetStfring(delim);
string[] sep = new string[] { delims };
string[] res = thefile.Split(sep, StringSplitOptions.None);
int curr = 0;
foreach(string result in res)
{
byte[] thing = Encoding.Unicode.GetBytes(res[curr]);
File.WriteAllBytes("split" + curr, thing);
curr++;
}
This doesn't happen if I use Encoding.UTF8, but some data is lost (FF -> EF BF BD in hex).
Does anyone have any suggestions?
Related
I have a large file, I need to search in it for a sequence of 7 bytes and return the position of that sequence in that files. I can't post any code because so far I was not able to write any decent code. Can anyone please point me in the right direction? Maybe is there a function that I don't know the existence of?
Example
Given a file like that:
I want to find the position of F8 1E 13 B9 E4 28 88 which in this case is at 0x21
Here's a nice extension method to do it:
public static class ByteArrayExtensions
{
public static int IndexOf(this byte[] sequence, byte[] pattern)
{
var patternLength = pattern.Length;
var matchCount = 0;
for (var i = 0; i < sequence.Length; i++)
{
if (sequence[i] == pattern[matchCount])
{
matchCount++;
if (matchCount == patternLength)
{
return i - patternLength + 1;
}
}
else
{
matchCount = 0;
}
}
return -1;
}
}
Then you can find it as follows:
var bytes = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x010 };
var index = bytes.IndexOf(new byte[] { 0x03, 0x04, 0x05 });
C# Question:
I need to be able to create array of sets of bytes with a variable assigned to each set of bytes return that set of bytes to go through a for each loop function until the list is finished for example:
public static bytes[] OBJECTS()
{
return new bytes[3]
{
public static byte[] object1 = new byte[] { 0xB7, 0x79, 0xA0, 0x91 };
public static byte[] object2 = new byte[] { 0x4C, 0x80, 0xEB, 0x0E };
public static byte[] object3 = new byte[] { 0x5D, 0x0A, 0xAC, 0x8F };
};
}
EXAMPLE
I need to be able to return every value in the array to the for loop to perform functions with every set of bytes. Sorry for the confusion.
for (int i = 0; i < 3; ++i)
{
1st Loop Return Object 1
2st Loop Return Object 2
3rd Loop Return Object 3
}
This code most closely resembles the code in your question, but this is legal C#. How close is this to what you want?
void Main()
{
for (int i = 0; i < 3; ++i)
{
byte[] selected = OBJECTS()[i];
/* do something with `selected` */
}
}
public static byte[][] OBJECTS()
{
return new byte[][]
{
new byte[] { 0xB7, 0x79, 0xA0, 0x91 },
new byte[] { 0x4C, 0x80, 0xEB, 0x0E },
new byte[] { 0x5D, 0x0A, 0xAC, 0x8F },
};
}
This would be a better way to get each sub-array:
foreach (byte[] selected in OBJECTS())
{
/* do something with `selected` */
}
I have a string text = 0a00...4c617374736e6e41. This string actually contains hex values as chars. What I am trying to do is to the following conversion, without changing e. g. the char a to 0x41;
text = 0a...4c617374736e6e41;
--> byte[] bytes = {0x0a, ..., 0x4c, 0x61, 0x73, 0x74, 0x73, 0x6e, 0x6e, 0x41};
This is what I tried to implement so far:
...
string text = "0a00...4c617374736e6e41";
var storage = StringToByteArray(text)
...
Console.ReadKey();
public static byte[] StringToByteArray(string text)
{
char[] buffer = new char[text.Length/2];
byte[] bytes = new byte[text.length/2];
using(StringReader sr = new StringReader(text))
{
int c = 0;
while(c <= text.Length)
{
sr.Read(buffer, 0, 2);
Console.WriteLine(buffer);
//How do I store the blocks in the byte array in the needed format?
c +=2;
}
}
}
The Console.WriteLine(buffer) gives me the two chars I need. But I have NO idea how to put them in the desired format.
Here are some links I already found in the topic, however I were not able to transfer that to my problem:
How would I read an ascii string of hex values in to a byte array?
How do you convert Byte Array to Hexadecimal String, and vice versa?
Try this
string text = "0a004c617374736e6e41";
List<byte> output = new List<byte>();
for (int i = 0; i < text.Length; i += 2)
{
output.Add(byte.Parse(text.Substring(i,2), System.Globalization.NumberStyles.HexNumber));
}
I am sending an API frame using the following code:
byte[] bytesToSend5 = new byte[]
{
0x7E, 0x00, 0x10, 0x01, 0x00, 0x13,
0xA2, 0x00, 0x40, 0xA6, 0x5E, 0x23,
0xFF, 0xFE, 0x02, 0x44, 0x37, 0x04, 0x4D
};
serialPort1.Write(bytesToSend5, 0, bytesToSend5.Length);
It's split up like this:
byte[] bytesToSend5 = new byte[]
{
5Startbits(won't change),
8IDbits(changes when a part of the device is swapped),
6determinationbits(tells the device what to do),
1checksumbit(calculated based on previous bits)
};
The first code example works as is desired with the current product. If, for whatever reason, a part of the device needs to be changed, it will not work because the ID bits won't fit. The ID number is printed on the device, 16 digits with numbers and letters, such as "0013A20043A25E86".
What I want to do is make a textbox where the user can input the new ID number and it will be replaced with the appropriate bits in the aforementioned byte array.
Here is my attempt using the Array.Copy function, trying to display the result in a textbox - but no change is detected. I've tried typing "1" "1,2,3" etc as well as the actual ID's "0013A20043A25E86":
string xbee_serienr = prop1_serienr.Text;
byte[] front = { 0x7E, 0x00, 0x10, 0x17, 0x01 };
byte[] back = { 0xFF, 0xFE, 0x02, 0x44, 0x37, 0x04 };
string[] xbee = { xbee_serienr };
byte[] combined = new byte[front.Length + xbee.Length + back.Length];
Array.Copy(front, combined, front.Length);
Array.Copy(back, 0, combined, 5, back.Length);
var result = string.Join(",", combined.Select(x => x.ToString()).ToArray());
OutputWindow.Text = result;
It would have to be possible to change the 8ID bits based on user input, and calculate the last checksum bit based on the rest of the bits.
I have searched the internet and tried Array.copy, Concat etc. but I haven't made any progress with it. Any guidance or input on this would be highly appreciated, even if it means guiding me in a direction of taking a different approach.
EDIT:
I now have the desired information in the byte array "result" using roughly the same example as below (taking user input for the var "xbee_serienr"). I now want to pass this to a method that looks like this:
private void button_D07_Lav_Click(object sender, EventArgs e)
{
byte[] bytesToSend5 = new byte[] { 0x7E, 0x00, 0x10, 0x01, 0x00, 0x13, 0xA2, 0x00, 0x40, 0xA6, 0x5E, 0x23, 0xFF, 0xFE, 0x02, 0x44, 0x37, 0x04, 0x4D };
serialPort1.Write(bytesToSend5, 0, bytesToSend5.Length);
And make the "bytesToSend5" use the array "result" from the other method.
I've tried using this example, like so:
byte result { get; set; } //above and outside of the two methods
var result = string.Join(string.Empty, combined.Select(x => x.ToString("X2")).ToArray()); //this is the end of the first method
private void button_D07_Lav_Click(object sender, EventArgs e)
{
byte[] bytesToSend5 = new byte[] { 0x7E, 0x00, 0x10, 0x01, 0x00, 0x13, 0xA2, 0x00, 0x40, 0xA6, 0x5E, 0x23, 0xFF, 0xFE, 0x02, 0x44, 0x37, 0x04, 0x4D };
bytesToSend5 = result; //using the array stored in result instead of the one currently in bytesToSend5.
serialPort1.Write(bytesToSend5, 0, bytesToSend5.Length);
}
I realize the obvious problem here, that it's not on the same form. This is why I wanted to split the array and add 0x in front of every item in the array, and separate them with commas.
I'm also going to use this for several different devices once I figure it out properly, which makes me fear there will be a lot of duplicated code, but I suspect once I'm understanding how to pass and use the array in a different method, I can always "duplicate" the code for every device, since the ID will indeed need to be different for the different devices.
Well, you never add the parsed string.
var xbee_serienr = "0013A20043A25E86";
byte[] front = { 0x7E, 0x00, 0x10, 0x17, 0x01 };
byte[] back = { 0xFF, 0xFE, 0x02, 0x44, 0x37, 0x04 };
var xbee = new byte[xbee_serienr.Length / 2];
for (var i = 0; i < xbee.Length; i++)
{
xbee[i] = byte.Parse(xbee_serienr.Substring(i * 2, 2), NumberStyles.HexNumber);
}
byte[] combined;
using (var ms = new MemoryStream(front.Length + xbee.Length + back.Length))
{
ms.Write(front, 0, front.Length);
ms.Write(xbee, 0, xbee.Length);
ms.Write(back, 0, back.Length);
combined = ms.ToArray();
}
var result = string.Join(string.Empty, combined.Select(x => x.ToString("X2")).ToArray());
Since you're adding multiple arrays one after another, I just used a MemoryStream. If you already have the byte[] ready (and mutable), you can write directly to that byte array and avoid allocating (and collecting) the extra array, but it doesn't make much of a difference when the limiting factor is the UI anyway.
My string contains the bytes (e.g 0x27), basically what I need to do is convert that string array which contains the byte data to a byte data type, so then I can encode it in UTF8, so it displays meaningful info.
1 string array contains:
0x37, 0x32, 0x2d, 0x38, 0x33, 0x39, 0x37, 0x32,0x2d, 0x30, 0x31
I need that converted to a byte array, is that possible?
My code is:
string strData;
string strRaw;
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.InnerXml = Data;
XmlElement xmlDocElement = xmlDoc.DocumentElement;
strData = xmlDocElement.GetAttribute("datalabel").ToString();
strRaw = xmlDocElement.GetAttribute("rawdata").ToString();
string[] arrData = strData.Split(' ');
string[] arrRaw = strRaw.Split(' ');
Thanks for any help.
To say the 'string contains the bytes' could be interpreted in a few ways. You can extract a string into bytes in a number of ways. Converting a string directly into bytes based on UTF8 encoding:
var inputBytes = System.Text.Encoding.UTF8.GetBytes(input);
There are of course similar methods for other encodings.
Ignore the above
Your comment changes the way the question reads quite a bit! If your strings are just hex (i.e. the bytes are not encoded into the string) just convert from hex to integers. Something like....
var b = Convert.ToUInt32(str.Substring(2), 16)
// For an array
var bytes = new byte[arrData.Length];
for(var i = 0; i < arrData.Length; i++) {
bytes[i] = (byte)Convert.ToUInt32(arrData[i].Substring(2), 16);
}
If you have each byte in a char and just want to convert it to a byte array without using an encoding, use;
string blip = "\x4A\x62";
byte[] blop = (from ch in blip select (byte)ch).ToArray();
If you want to convert it using UTF8 encoding right away, use
string blip = "\x4A\x62";
var blop = System.Text.Encoding.UTF8.GetBytes(blip);
given your string is "0x37, 0x32, 0x2d, 0x38, 0x33, 0x39, 0x37, 0x32,0x2d, 0x30, 0x31" or similar you can get the byte values like this;
string input = "0x37, 0x32, 0x2d, 0x38, 0x33, 0x39, 0x37, 0x32, 0x2d, 0x30, 0x31";
string[] bytes = input.Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries);
byte[] values = new byte[bytes.Length];
for (int i = 0; i < bytes.Length; i++)
{
values[i] = byte.Parse(bytes[i].Substring(2,2), System.Globalization.NumberStyles.AllowHexSpecifier);
Console.WriteLine(string.Format("{0}", values[i]));
}
once you have them you need to feed them into an apropriate Encoder/Decoder to get the string.
You should be able to do the following:
System.Text.UTF8Encoding encoding=new System.Text.UTF8Encoding();
byte[] bytes = encoding.GetBytes(str);