how to continue a loop despite error in parsing byte data - c#

my question is a continuation of this: (loop for reading different data types & sizes off very large byte array from file)
I have a raw byte stream stored on a file (rawbytes.txt or bytes.data) that I need to parse and output to a CSV-style text file.
The input of raw bytes (when read as characters/long/int etc.) looks something like this:
A2401028475764B241102847576511001200C...
Parsed it should look like:
OutputA.txt
(Field1,Field2,Field3) - heading
A,240,1028475764
OutputB.txt
(Field1,Field2,Field3,Field4,Field5) - heading
B,241,1028475765,1100,1200
OutputC.txt
C,...//and so on
Essentially, it's a hex-dump-style input of bytes that is continuous without any line terminators or gaps between data that needs to be parsed. The data, as seen above, consists of different data types one after the other.
Here's a snippet of my code - because there are no commas within any field, and no need arises to use "" (i.e. a CSV wrapper), I'm simply using TextWriter to create the CSV-style text file as follows:
if (File.Exists(fileName))
{
using (BinaryReader reader = new BinaryReader(File.Open(fileName, FileMode.Open)))
{
while (reader.BaseStream.Position != reader.BaseStream.Length)
{
inputCharIdentifier = reader.ReadChar();
switch (inputCharIdentifier)
case 'A':
field1 = reader.ReadUInt64();
field2 = reader.ReadUInt64();
field3 = reader.ReadChars(10);
string strtmp = new string(field3);
//and so on
using (TextWriter writer = File.AppendText("outputA.txt"))
{
writer.WriteLine(field1 + "," + field2 + "," + strtmp); // +
}
case 'B':
//code...
My question is based on the fact that some of the raw byte data contains null values, which are difficult to parse through - because there are an unknown number of null bytes (or non-null, out-of-place bytes) between consecutive data blocks (each starting with A, B or C if the data blocks are not corrupt).
QUESTION
So, how do I add a default case or some other mechanism to continue with the loop despite an error that might arise because of corrupt or faulty data? Is the following code something that would work?
inputCharIdentifier = reader.ReadChar();
...
case default:
//I need to know what to add here, instead of default
//(i.e. the case when the character could not be read)
while (binReader.PeekChar() != -1)
{
filling = binReader.readByte();
//filling is a single byte
try {
fillingChar = Convert.ToChar(filling);
break;
}
catch (Exception ex) { break; }
if (fillingChar == 'A' || fillingChar == 'B')
break;
The remaining part - adding code to each switch case (eg 'A') to continue without stopping the program - is there a way to do this without multiple try-catch blocks? [i.e. the code block character identifier is A, but the bytes after A are corrupt - in which case i need to exit the loop OR read (i.e. skip over) a defined number of bytes - which here, would be known if the message header correctly identifies the remaining bytes.
[Note: Case A, B and so on have different sized input - in other words, A might be 40 bytes total, while B is 50 bytes. So the use of a fixed size buffer, say inputBuf[1000], or [50] for instance - if they were all the same size - wouldn't work well either, AFAIK.]
Any suggestions? Please help! I'm relatively new to C# (2 months)...
Update: my entire code is as follows:
class Program
{
const string fileName = "rawbytes.txt";
static void Main(string[] args)
{
try
{
var program = new Program();
program.Parser();
}
catch (Exception e)
{
Console.WriteLine(e);
}
Console.ReadLine();
}
public void Parser()
{
char inputCharIdentifier = 'Z';
//only because without initializing inputCharIdentifier I ended up with an error
//note that in the real code, 'Z' is not a switch-case alphabet
//it's an "inconsequential character", i.e. i have defined it to be 'Z'
//just to avoid that error, and to avoid leaving it as a null value
ulong field1common = 0;
ulong field2common = 0;
char[] charArray = new char[10];
char char1;
char char2;
char char3;
int valint1 = 0;
int valint2 = 0;
int valint3 = 0;
int valint4 = 0;
int valint5 = 0;
int valint6 = 0;
int valint7 = 0;
double valdouble;
/*
char[] filler = new char[53];
byte[] filling = new byte[4621];
byte[] unifiller = new byte[8];
//these values above were temporary measures to manually filter through
//null bytes - unacceptable for the final program
*/
if (File.Exists(fileName))
{
using (BinaryReader reader = new BinaryReader(File.Open(fileName, FileMode.Open)))
{
while (reader.BaseStream.Position != reader.BaseStream.Length)
{
//inputCharIdentifier = reader.ReadChar();
//if (inputCharIdentifier != null)
//{
try
{
inputCharIdentifier = reader.ReadChar();
try
{
switch (inputCharIdentifier)
{
case 'A':
field1common = reader.ReadUInt64();
field2common = reader.ReadUInt64();
//unifiller = reader.ReadBytes(8);
//charArray = reader.ReadString();
//result.ToString("o");
//Console.WriteLine(result.ToString());
charArray = reader.ReadChars(10);
string charArraystr = new string(charArray);
char1 = reader.ReadChar();
valint1 = reader.ReadInt32();
valint2 = reader.ReadInt32();
valint3 = reader.ReadInt32();
valint4 = reader.ReadInt32();
using (TextWriter writer = File.AppendText("A.txt"))
{
writer.WriteLine(field1common + "," + /*result.ToString("o")*/ field2common + "," + charArraystr + "," + char1 + "," + valint1 + "," + valint2 + "," + valint3 + "," + valint4);
writer.Close();
}
break;
case 'B':
case 'C':
field1common = reader.ReadUInt64();
field2common = reader.ReadUInt64();
//charArray = reader.ReadString();
charArray = reader.ReadChars(10);
string charArraystr2 = new string(charArray);
char1 = reader.ReadChar();
valint1 = reader.ReadInt32();
valint2 = reader.ReadInt32();
using (TextWriter writer = File.AppendText("C.txt"))
{
writer.WriteLine(field1common + "," + result2.ToString("o") + "," + charArraystr2 + "," + char1 + "," + valint1 + "," + valint2);
writer.Close();
}
break;
case 'S':
//market status message
field1common = reader.ReadUInt64();
char2 = reader.ReadChar();
char3 = reader.ReadChar();
break;
case 'L':
filling = reader.ReadBytes(4);
break;
case 'D':
case 'E':
field1common = reader.ReadUInt64();
field2common = reader.ReadUInt64();
//charArray = reader.ReadString();
charArray = reader.ReadChars(10);
string charArraystr3 = new string(charArray);
//char1 = reader.ReadChar();
valint1 = reader.ReadInt32();
valint2 = reader.ReadInt32();
valint5 = reader.ReadInt32();
valint7 = reader.ReadInt32();
valint6 = reader.ReadInt32();
valdouble = reader.ReadDouble();
using (TextWriter writer = File.AppendText("D.txt"))
{
writer.WriteLine(field1common + "," + result3.ToString("o") + "," + charArraystr3 + "," + valint1 + "," + valint2 + "," + valint5 + "," + valint7 + "," + valint6 + "," + valdouble);
writer.Close();
}
break;
}
}
catch (Exception ex)
{
Console.WriteLine("Parsing didn't work");
Console.WriteLine(ex.ToString());
break;
}
}
catch (Exception ex)
{
Console.WriteLine("Here's why the character read attempt didn't work");
Console.WriteLine(ex.ToString());
continue;
//continue;
}
//}
}
}
}
}
The error I receive is as follows:
Here's why the character read attempt didn't work
System.ArgumentException: The output char buffer is too small to contain the decoded characters, encoding 'Unicode (UTF-8)' fallback 'System.Text.DecoderReplacementFallback'.
Parameter name: chars
at System.Text.Encoding.ThrowCharsOverflow()
at System.Text.Encoding.ThrowCharsOverflow(DecoderNLS decoder, Boolean nothingDecoded)
at System.Text.UTF8Encoding.GetChars(Byte* bytes, Int32 byteCount, Char* chars, Int32 charCount, DecoderNLS baseDecoder)
at System.Text.DecoderNLS.GetChars(Byte* bytes, Int32 byteCount, Char* chars, Int32 charCount, Boolean flush)
at System.Text.DecoderNLS.GetChars(Byte[] bytes, Int32 byteIndex, Int32 byteCount, Char[] chars, Int32 charIndex, Boolean flush)
at System.Text.DecoderNLS.GetChars(Byte[] bytes, Int32 byteIndex, Int32 byteCount, Char[] chars, Int32 charIndex)
at System.IO.BinaryReader.InternalReadOneChar()
at System.IO.BinaryReader.Read()
at System.IO.BinaryReader.ReadChar()
at line 69: i.e. inputCharIdentifier = reader.ReadChar();
Update: A sample file that generates the same error above is at the following link:
http://www.wikisend.com/download/106394/rawbytes.txt
Notice in particular the 8 unexpected null bytes between successive data blocks, even though the data block header - i.e. inputCharIdentifier - is valid. The number of bytes that follows such a header is always unpredictable and generally varies. My issue is that I need to be able to either delete or skip over such a situation when it arises to the next non-corrupt data block available - in the case of the sample file, the last (single) data block that occurs after the 8 out-of-place null bytes.
The 8 null bytes can be located in the file as follows:
Byte Counter: 1056
Line 2, Column 783 (according to Notepad++)
The crux of the problem is that the 8 null bytes can be any size - 3, 7, 15, 50, etc. It is always unknown - as a direct result of data corruption. But unlike "traditional" data corruption, i.e. where a fixed number of bytes, say 50, inside a data block that might be unreadable and can therefore be skipped over (by that exact number of bytes) - the data corruption i face consists of an unknown number of bytes between valid data blocks.

You cannot assign a case for these situations because the target variable (inputCharIdentifier) is null; thus it is enough with a condition avoiding these cases. I have also included a try...catch, just to make completely sure (any error while performing all the given actions would make the code to automatically skip to the following iteration).
try
{
using (BinaryReader reader = new BinaryReader(File.Open(fileName, FileMode.Open), Encoding.ASCII))
{
while (reader.BaseStream.Position != reader.BaseStream.Length)
{
inputCharIdentifier = reader.ReadChar();
if(inputCharIdentifier != null)
{
switch (inputCharIdentifier)
case 'A':
field1 = reader.ReadUInt64();
field2 = reader.ReadUInt64();
field3 = reader.ReadChars(10);
string strtmp = new string(field3);
//and so on
using (TextWriter writer = File.AppendText("outputA.txt"))
{
writer.WriteLine(field1 + "," + field2 + "," + strtmp);
}
case 'B':
//code...
}
}
}
}
catch
{
}

Related

Keep the last eight bytes when reading raw image file with C#

Im trying to read a raw image file with C# and keep the last 2 bytes, and last 8 bytes in a variable. However there is something wrong in my if-statement so the variables just appends.. Like this:
twoBytes= eightBytes=
twoBytes=00 eightBytes=00
twoBytes=0000 eightBytes=0000
twoBytes=000000 eightBytes=000000
twoBytes=00000000 eightBytes=00000000
twoBytes=0000000000 eightBytes=0000000000
twoBytes=000000000000 eightBytes=000000000000
twoBytes=00000000000000 eightBytes=00000000000000
twoBytes=0000000000000000 eightBytes=0000000000000000
twoBytes=000000000000000000 eightBytes=000000000000000000
twoBytes=00000000000000000000 eightBytes=00000000000000000000
twoBytes=0000000000000000000000 eightBytes=0000000000000000000000
twoBytes=000000000000000000000000 eightBytes=000000000000000000000000
twoBytes=00000000000000000000000000 eightBytes=00000000000000000000000000
twoBytes=0000000000000000000000000000 eightBytes=0000000000000000000000000000
twoBytes=000000000000000000000000000000 eightBytes=000000000000000000000000000000
twoBytes=00000000000000000000000000000000 eightBytes=00000000000000000000000000000000
twoBytes=0000000000000000000000000000000000 eightBytes=0000000000000000000000000000000000
twoBytes=000000000000000000000000000000000000 eightBytes=000000000000000000000000000000000000
twoBytes=00000000000000000000000000000000000000 eightBytes=00000000000000000000000000000000000000
I want something like "twoBytes=55AA", and eightBytes="55AA454649205041"
My code:
// Read file, byte at the time (example 00, 5A)
FileStream fs = new FileStream("C:\\Users\\user\\image_files\\usb_guid_exfat.001", FileMode.Open);
int hexIn;
String hex;
String twoBytes = "";
String eightBytes = "";
for (int i = 0; (hexIn = fs.ReadByte()) != -1; i++)
{
hex = string.Format("{0:X2}", hexIn);
Console.WriteLine("twoBytes=" + twoBytes + " eightBytes=" + eightBytes);
// Transfer two bytes
twoBytes = twoBytes + hex;
if (twoBytes.Length < 4)
{
if (twoBytes.Length > 6) {
twoBytes = twoBytes.Substring(2, 4);
}
}
// Transfer eight bytes
eightBytes = eightBytes + hex;
if(eightBytes.Length < 8)
{
if (twoBytes.Length > 10) {
eightBytes = eightBytes.Substring(2, 8);
}
}
}
Your if statements are wrong. A value can't be less than 4 and greater than 6 at the same time.
If length is <=4, you have 1 or 2 bytes, so you need to inspect only if length is grater than 4 (6,8,etc). Otherwise the value stays the same.
The code for inspecting string bigger than 4:
twoBytes = twoBytes + hex;
if (twoBytes.Length > 4) {
twoBytes = twoBytes.Substring(twoBytes.Length-4, 4);
}
The similar with eightBytes.
Good luck!! :)

How to convert Android AudioFormat.ENCODING_PCM_16BIT into uLaw or Linear in C#

I have developed two UDP multicast apps using .NET and Android. Both applications have Sender and Receiver. They are working well when I am using the same app on different devices/pc. But when I try to receive the stream from .NET App to Android or Android to .NET then getting noise voice. I have checked both apps' streaming metadata (byte) and their format is different. Android Audio Format is: AudioFormat.ENCODING_PCM_16BIT for Encoding and C# Receiver convert the coming bytes uLaw To Linear. I understand due to different algorithm implementation in both app, they are not taking the stream. Please check my code snippets for C# & Android.
C# Codes
public static Byte[] MuLawToLinear(Byte[] bytes, int bitsPerSample, int channels)
{
//Anzahl Spuren
int blockAlign = channels * bitsPerSample / 8;
//Für jeden Wert
Byte[] result = new Byte[bytes.Length * blockAlign];
for (int i = 0, counter = 0; i < bytes.Length; i++, counter += blockAlign)
{
//In Bytes umwandeln
int value = MulawToLinear(bytes[i]);
Byte[] values = BitConverter.GetBytes(value);
switch (bitsPerSample)
{
case 8:
switch (channels)
{
//8 Bit 1 Channel
case 1:
result[counter] = values[0];
break;
//8 Bit 2 Channel
case 2:
result[counter] = values[0];
result[counter + 1] = values[0];
break;
}
break;
case 16:
switch (channels)
{
//16 Bit 1 Channel
case 1:
result[counter] = values[0];
result[counter + 1] = values[1];
break;
//16 Bit 2 Channels
case 2:
result[counter] = values[0];
result[counter + 1] = values[1];
result[counter + 2] = values[0];
result[counter + 3] = values[1];
break;
}
break;
}
}
return result;
}
Android Codes
// Audio Configuration.
int sampleRate = 16000; // How much will be ideal?
int channelConfig = AudioFormat.CHANNEL_IN_MONO;
int audioFormat = AudioFormat.ENCODING_PCM_16BIT;
boolean status = true;
String ip = getIntent().getStringExtra("ip");
final InetAddress destination = InetAddress
.getByName(ip);
recorder = new AudioRecord(MediaRecorder.AudioSource.MIC,
sampleRate, channelConfig, audioFormat, minBufSize);
recorder.startRecording();
while (status) {
if (!startStreamThread) {
socket.disconnect();
socket.leaveGroup(destination);
break;
}
byte[] bytes = new byte[2 + buffer.length];
bytes[0] = 1;
bytes[1] = 2;
System.arraycopy(buffer, 0, bytes, 2, buffer.length);
String deviceIp = getIpAddress();
minBufSize = recorder.read(bytes, 0, bytes.length);
// putting buffer in the packet
packet = new DatagramPacket(bytes, bytes.length,
destination, DEFAULT_PORT);
Log.e("NewOutgoing", "" + packet.getData());
Log.e("NewDEstination; ", "" + destination);
// packet.setData(deviceIp.getBytes());
socket.send(packet);
}

C# Reading String inside a binary file

I have some problems to understand how reading files from different format than the text format. I know that inside a given file there are some information as string. I managed to write the hex code to a text file which is helping me a lot for another function of the process, because I know that after some combinations of hex codes there might be string writed in the file.
For instance, I have this batch of hex codes.
00 39 AF 32 DD 24 BA 09 07 06 03 DB
I know that when the hex codes are equal to AF 32 the next information should be the string. For instance: "Invoice Number 223232"
Any help or reference will be appreciated.
Kind regards,
static void Main(string[] args)
{
StreamWriter writer = new StreamWriter("output.txt", true);
FileStream fs = new FileStream("File", FileMode.Open);
int hexIn;
String hex;
for (int i = 0; (hexIn = fs.ReadByte()) != -1; i++)
{
writer.Write(hexIn + " ");
hex = string.Format("{0:X2}", hexIn);
writer.Write(hex + " ");
}
}
The sample code you have looks like you are trying to read a binary file, not a hex-encoded text file.
If the source file is binary (which is ideal), you would read it byte-by-byte, and run through a state machine to know when to expect a string. You would have to know how long the string is. In the sample below I am assuming a null-terminated C-style string. For pascal style strings you would read a length prefix, or for fixed width just keep track of the expected number of character.
bool done = false;
int state = 0;
StringBuilder result = new StringBuilder();
while (!done) {
int byteValue = fs.ReadByte();
if (bytesValue == -1)
done = true;
else {
switch (state) {
case 0: //looking for 0xAF
if (byteValue == 0xAF)
state = 1;
break;
case 1: //looking for 0x32
if (byteValue == 0x32)
state = 2;
else
state = 0;
break;
case 2: //start reading string
if (byteValue == 0) {//end of C-style string
//Do something with result.ToString()
result.Clear();
state = 0; //go back to looking for more strings
} else {
result.Append((char)byteValue); //assuming 8-bit ASCII string
}
break;
}
}
}
If you are reading a hex-encoded text file, it would be more difficult, as you would have to read hex nibbles at a time and reconstruct the bytes, but the state machine approach would be similar.

Generate 1 MB (or n MB) text file in C#

I need to create a text file (alphanumeric) with size (exact or nearly) in MB equal to my input number, such as 1 MB. I tried to generated a string, with think that one char is 16 bit or 2 byte, so:
1KB = 1024 Bytes = 1024 x 8 Bits = 1024 x 8 / 16 chars = 512 chars.
But the generated file is not very seem to be right :(
If I generate byte array and write it to file, the size is pretty correct!
public static void generateDummyFileBySize(long sizeInMb, string filePath) {
byte[] data = new byte[sizeInMb * 1024 * 1024];
Random rng = new Random();
rng.NextBytes(data);
File.WriteAllBytes(filePath, data);
}
Help me please. This is the code I used to generated text file
public static String generateStringSize(long sizeByte)
{
StringBuilder sb = new StringBuilder();
Random rd = new Random();
/**
* Byte -> Bit -> Divide by 16 to num of char
* */
var numOfChars = sizeByte * 8 ;
string allows = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
int maxIndex = allows.Length - 1;
for (int i = 0; i < numOfChars; i++)
{
int index = rd.Next(maxIndex);
char c = allows[index];
sb.Append(c);
}
return sb.ToString();
}
public static void generateTextFileBySize(long size, string fileName)
{
long sizeOld = size;
try
{
String s;
String path = Directory.GetCurrentDirectory();
var physicPath = path + Path.DirectorySeparatorChar + fileName;
File.Delete(physicPath);
if (size <= MAX_SIZE)
{
s = StringUtil.generateStringSize(size);
Console.WriteLine("Generated a string with length " + size);
File.WriteAllText(physicPath, s, Encoding.UTF8);
}
else
{
while (size > MAX_SIZE)
{
s = StringUtil.generateStringSize(MAX_SIZE);
Console.WriteLine("Appending " + MAX_SIZE + " to file");
File.AppendAllText(physicPath, s, Encoding.UTF8);
size -= MAX_SIZE;
}
s = StringUtil.generateStringSize(size);
File.AppendAllText(physicPath, s, Encoding.UTF8);
}
Console.WriteLine("Created file named " + fileName + " with size " + sizeOld + " bytes.");
}
catch (Exception ex)
{
Console.WriteLine("Error when generating file");
Console.WriteLine(ex.Message);
}
}
The problem lies here:
var numOfChars = sizeByte * 8 ;
You create eight times the characters you need. Instead just use
var numOfChars = sizeByte;
Each of the characters you use occupies one byte when stored as UTF-8, so you don't need to use a different number of characters than the number of bytes you want.
Made following changes to your code:
Removed 8 from var numOfChars = sizeByte*8;, since in ASCII encoding, each character is 1 byte also changed the Encoding to ASCII instead of UTF8 to be precise for characters.
Following is the working code, generates precise 1 MB file, I have tested for other values like 8 MB, 7 MB, result is accurate
String s = generateStringSize(1024 * 1024);
File.WriteAllText("D:\\Test1.txt", s, Encoding.ASCII);

BitConverter.ToString() in reverse? [duplicate]

This question already has answers here:
How do you convert a byte array to a hexadecimal string, and vice versa?
(53 answers)
Closed 8 years ago.
I have an array of bytes that I would like to store as a string. I can do this as follows:
byte[] array = new byte[] { 0x01, 0x02, 0x03, 0x04 };
string s = System.BitConverter.ToString(array);
// Result: s = "01-02-03-04"
So far so good. Does anyone know how I get this back to an array? There is no overload of BitConverter.GetBytes() that takes a string, and it seems like a nasty workaround to break the string into an array of strings and then convert each of them.
The array in question may be of variable length, probably about 20 bytes.
Not a built in method, but an implementation. (It could be done without the split though).
String[] arr=str.Split('-');
byte[] array=new byte[arr.Length];
for(int i=0; i<arr.Length; i++) array[i]=Convert.ToByte(arr[i],16);
Method without Split: (Makes many assumptions about string format)
int length=(s.Length+1)/3;
byte[] arr1=new byte[length];
for (int i = 0; i < length; i++)
arr1[i] = Convert.ToByte(s.Substring(3 * i, 2), 16);
And one more method, without either split or substrings. You may get shot if you commit this to source control though. I take no responsibility for such health problems.
int length=(s.Length+1)/3;
byte[] arr1=new byte[length];
for (int i = 0; i < length; i++)
{
char sixteen = s[3 * i];
if (sixteen > '9') sixteen = (char)(sixteen - 'A' + 10);
else sixteen -= '0';
char ones = s[3 * i + 1];
if (ones > '9') ones = (char)(ones - 'A' + 10);
else ones -= '0';
arr1[i] = (byte)(16*sixteen+ones);
}
(basically implementing base16 conversion on two chars)
You can parse the string yourself:
byte[] data = new byte[(s.Length + 1) / 3];
for (int i = 0; i < data.Length; i++) {
data[i] = (byte)(
"0123456789ABCDEF".IndexOf(s[i * 3]) * 16 +
"0123456789ABCDEF".IndexOf(s[i * 3 + 1])
);
}
The neatest solution though, I believe, is using extensions:
byte[] data = s.Split('-').Select(b => Convert.ToByte(b, 16)).ToArray();
If you don't need that specific format, try using Base64, like this:
var bytes = new byte[] { 0x12, 0x34, 0x56 };
var base64 = Convert.ToBase64String(bytes);
bytes = Convert.FromBase64String(base64);
Base64 will also be substantially shorter.
If you need to use that format, this obviously won't help.
byte[] data = Array.ConvertAll<string, byte>(str.Split('-'), s => Convert.ToByte(s, 16));
I believe the following will solve this robustly.
public static byte[] HexStringToBytes(string s)
{
const string HEX_CHARS = "0123456789ABCDEF";
if (s.Length == 0)
return new byte[0];
if ((s.Length + 1) % 3 != 0)
throw new FormatException();
byte[] bytes = new byte[(s.Length + 1) / 3];
int state = 0; // 0 = expect first digit, 1 = expect second digit, 2 = expect hyphen
int currentByte = 0;
int x;
int value = 0;
foreach (char c in s)
{
switch (state)
{
case 0:
x = HEX_CHARS.IndexOf(Char.ToUpperInvariant(c));
if (x == -1)
throw new FormatException();
value = x << 4;
state = 1;
break;
case 1:
x = HEX_CHARS.IndexOf(Char.ToUpperInvariant(c));
if (x == -1)
throw new FormatException();
bytes[currentByte++] = (byte)(value + x);
state = 2;
break;
case 2:
if (c != '-')
throw new FormatException();
state = 0;
break;
}
}
return bytes;
}
it seems like a nasty workaround to break the string into an array of strings and then convert each of them.
I don't think there's another way... the format produced by BitConverter.ToString is quite specific, so if there is no existing method to parse it back to a byte[], I guess you have to do it yourself
the ToString method is not really intended as a conversion, rather to provide a human-readable format for debugging, easy printout, etc.
I'd rethink about the byte[] - String - byte[] requirement and probably prefer SLaks' Base64 solution

Categories