My code here reads all the bytes of a image and stores it in the byte array. Is there a way to convert these bytes into ascii then split them up to 512-char(ascii char) long pieces? Like when you try splitting a string based on the length, you can do that. Can you do something similar to splitting this into 512 lengths? This is to send to the server.
byte[] imagesize;
imagesize = File.ReadAllBytes(#"C:\image.jpeg");
Console.Write(imagesize[1].ToString());
What I really want is to convert these bytes into plain ASCII format (Which in C# would be Encoding.ASCII), then split that long ASCII line from converting all the bytes into 512-char(?) long chunks into a byte array (byte[] chunks). So when I send the packets I can do
for(i=0; i<AmountOfChunks; i++)
{
Packet.payload = chunks[i];
//The "chunks" is the ASCII formated array.
}
If someone knows how to do this, it would greatly help. Thanks, if there's anything more, i'll try to explain it in more detail if i can.
If this is wrong, because i know a byte is 8-bit each. Then somehow to be able to do it, maybe the bytes into a list?
Not clear why you needs this, but you might be looking for Convert.ToBase64String() to get a string representation. For chunking you can just walk over the resulting string and split at the appropriate indexes:
byte[] imagesize = File.ReadAllBytes(#"C:\image.jpeg");
string base64String = Convert.ToBase64String(imagesize);
List<string> chunks = new List<string>();
for (int i = 0; i < base64String.Length; i+=512)
{
chunks.Add(base64String.Substring(i, Math.Min(512, base64String.Length - i)));
}
Try to make this
int i=0;
do
{
sendBytes = imagesize.Skip(512*i).Take(512).ToArray();
//Your function of send
i++;
}
while(imagesize.Count()-512*i>0)
Related
I am receiving data from a cnc machine every 5 seconds. Length of the data is 66 bytes. And every two byte has a special meaning according to the guide that I have. The device sends the data over socket to a specific ip and port. I have been told that I should read the data as hex instead of ascii.
This line of code returns
string data = Encoding.ASCII.GetString(data.buffer,0,66);
this;
"\0\u0004\0\u0001\0\0\0\0\0\0\0\0\0\0\0\0\0\r\0\r\0\0\0\0\0\0:a\u0002#\0?\0`\u001b?\u0015U\0\0\0\0\u0001\u0010\0\u0018\0\0\u000f\a\0\0\0\0\0\0\0\0\0\0\0\0\0\0u/"
and of course it is not useful to me.
I did tried to convert byte array to the hex string with that code;
StringBuilder sb = new StringBuilder();
foreach (byte b in buffer)
sb.Append(b.ToString("X2"));
string hexString = sb.ToString();
And got result as
00040001000000000000000000020000000000000000000000003A9D023F00A000601B841555000000000110001800000F070000000000000000000000000000752F
And when I try to convert this result as string, no success, nothing meaningfull.
GOAL
What I am trying to achieve is, read the incoming socket data as hex and use every two byte as a word to match a value. For example first 2 byte should match either 0 or 1. With i have it returns ? (question mark)
Thank you.
I have been told that I should read the data as hex instead of ascii
My gut feeling is this statement has been misquoted or misunderstood. There is no value in processing binary data as string hex representation just as there is no value in converting it to ascii... The only sane way to process binary data, is in binary unless you have a meaningful way to convert it.
You mention you need word (2byte) groupings, you could just convert this to an array of short, or ushort depending on your needs
var bytes = new byte[66];
var shortArray = new short[bytes.Length / 2];
Buffer.BlockCopy(bytes, 0, shortArray, 0, bytes.Length);
or
for (int i = 0; i < shortArray.Length; i++)
shortArray[i] = BitConverter.ToInt16(bytes[(i*2)..(i*2+2)]);
Disclaimer : This is just an example, be very careful of the endianess of your data, there are other ways to do this
The task is to take a picture, read all its bytes and then write additional 15 zero bytes after each non-zero byte from original file. Example: it was B1,B2,...Bn and after it must be B1,0,0,..0,B2,0,0..,Bn,0,0..0. Then I need to save/replace new picture. In general I assume I can use something like ReadAllBytes and create an array of bytes, then create new byte[] array and take one byte from file, then write 15 zero bytes, then take second byte and etc. But how can I be sure that it is working correctly? I'm not familiar with working with bytes and if I try to print bytes that I've read from file it shows some random symbols that don't make any sense which leaves the question: am I doing it right? If possible, please direct me to right approach and the functions that I need to use to achieve it, thanks in advance!
See How to convert image to byte array for how to read the image.
It seems that you'd like to be able to visually see the data. For debugging purposes, you can show each byte as a hex string which will allow you to "see" the hex values of each element of your array.
public string GetBytesAsHexString(byte[] bArr)
{
StringBuilder sb = new StringBuilder();
if (bArr != null && bArr.Length > 0)
{
for (int i = 0; i < bArr.Length; i++)
{
sb.AppendFormat("{0}{1}", bArr[i].ToString("X"), System.Environment.NewLine);
//sb.AppendFormat("{0}{1}", bArr[i].ToString("X2"), System.Environment.NewLine);
//sb.AppendFormat("{0}{1}", bArr[i].ToString("X4"), System.Environment.NewLine);
}
}
return sb.ToString();
}
I have a simple bit of code that converts a C# string by encoding it to UTF-8 then creating a byte array from it. But i am wondering how can i encode to UTF-8 using a byte array i have already made at a starting index?
So this is how i am currently encoding and getting the resulting byte array:
byte[] result = Encoding.UTF8.GetBytes(myString);
But I have a byte array premade that i would prefer to write to at a specific index if that makes sense. Is there any built in method to do this, if not how would i go about it ?
GetBytes has another overload that writes to existing array:
byte[] bytes = new byte[1000]; // sample, make sure it has enough space
var specificIndex = 0;
var actualByteCount = Encoding.UTF8.GetBytes(
myString, 0, myString.Length, bytes, specificIndex);
Don't forget to handle result to know how many bytes in the array actually represent string (actualByteCount)
Note you may need to use GetByteCount to get correct array size or adjust number of characters to convert to fit into your buffer.
First you will need to convert your bytes into Base64String then convert that into bytes. Likes this:
byte[] random = new byte[] { 0x00C9, 0x00C9, 0x00C9 };
byte[] encodedBytes = Encoding.UTF8.GetBytes(Convert.ToBase64String(random));
I have a file containing some data (for example, "00927E2B112DB958......"). This data is a representation of bytes in ASCII form. The bytes are 8 bit, so 2 ASCII chars map to each byte that needs to go into the final output buffer array.
What is the best way to do this?
EDIT: What I am trying to do is go from a string that looks like "00DFFF" to a byte array of {0x00, 0xDF, 0xFF}, for example. I guess this wasn't clear.
Thanks!
private ICollection<byte> HexString2Ascii(string hexString)
{
var bytes = new List<byte>(hexString.Length / 2);
for (int i = 0; i <= hexString.Length - 2; i += 2)
bytes.Add(byte.Parse(hexString.Substring(i, 2), System.Globalization.NumberStyles.HexNumber));
return bytes;
}
I am writing a program that reads '.exe' files and stores their hex values in an array of bytes for comparison with an array containing a series of values. (like a very simple virus scanner)
byte[] buffer = File.ReadAllBytes(currentDirectoryContents[j]);
I have then used BitConverter to create a single string of these values
string hex = BitConverter.ToString(buffer);
The next step is to search this string for a series of values(definitions) and return positive for a match. This is where I am running into problems. My definitions are hex values but created and saved in notepad as defintions.xyz
string[] definitions = File.ReadAllLines(#"C:\definitions.xyz");
I had been trying to read them into a string array and compare the definition elements of the array with string hex
bool[] test = new bool[currentDirectoryContents.Length];
test[j] = hex.Contains(definitions[i]);
This IS a section from a piece of homework, which is why I am not posting my entire code for the program. I had not used C# before last Friday so am most likely making silly mistakes at this point.
Any advice much appreciated :)
It is pretty unclear exactly what kind of format you use of the definitions. Base64 is a good encoding for a byte[], you can rapidly convert back and forth with Convert.ToBase64String and Convert.FromBase64String(). But your question suggests the bytes are encoded in hex. Let's assume it looks like "01020304" for a new byte[] { 1, 2, 3, 4}. Then this helper function converts such a string back to a byte[]:
static byte[] Hex2Bytes(string hex) {
if (hex.Length % 2 != 0) throw new ArgumentException();
var retval = new byte[hex.Length / 2];
for (int ix = 0; ix < hex.Length; ix += 2) {
retval[ix / 2] = byte.Parse(hex.Substring(ix, 2), System.Globalization.NumberStyles.HexNumber);
}
return retval;
}
You can now do a fast pattern search with an algorithm like Boyer-Moore.
I expect you understand that this is a very inefficient way to do it. But except for that, you should just do something like this:
bool[] test = new bool[currentDirectoryContents.Length];
for(int i=0;i<test.Length;i++){
byte[] buffer = File.ReadAllBytes(currentDirectoryContents[j]);
string hex = BitConverter.ToString(buffer);
test[i] = ContainsAny(hex, definitions);
}
bool ContainsAny(string s, string[] values){
foreach(string value in values){
if(s.Contains(value){
return true;
}
}
return false;
}
If you can use LINQ, you can do it like this:
var test = currentDirectoryContents.Select(
file=>definitions.Any(
definition =>
BitConverter.ToString(
File.ReadAllBytes(file)
).Contains(definition)
)
).ToArray();
Also, make sure that your definitions-file is formatted in a way that matches the output of BitConverter.ToString(): upper-case with dashes separating each encoded byte:
12-AB-F0-34
54-AC-FF-01-02