How to define a byte array use the string style in .net? - c#

I want define a byte array like "\x90<>",
I can only define it use numbers
byte[] a = new byte[] { 0x90, 0x3c, 0x3e };
but it's not readable and cost more time to write,
Can I do something like this in .net?
byte[] a = '\x90<>';
Edited.
I'm ask this because in c and c++ I can actually define a byte array by
char myvar[] = "\x90<>"; or char *myvar= "\x90<>";
they are equals new byte[] { 0x90, 0x3c, 0x3e} on c#.

A string is an array of chars, where a char is not a byte in the .Net.
You can't define bytes with a string and you can't do this in easy way, you must implement your own convertor methods and use it with that.
Check this out:
static byte[] GetBytes(string str)
{
byte[] bytes = new byte[str.Length * sizeof(char)];
System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
static string GetString(byte[] bytes)
{
char[] chars = new char[bytes.Length / sizeof(char)];
System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
return new string(chars);
}

Try converting it to a char array in the declaration. The escaped characters will be correctly processed into a single char and the unescaped characters will be split into individual characters.
Then you can cast each element in the array as a byte. You could use LINQ to make it easy:
var bytes = "\x90<>".ToCharArray().Select(b => (byte)b);
foreach(var myByte in bytes){
Console.WriteLine(string.Format("0x{0:x2}", myByte));
}
I believe this gives you the correct output of 0x90, 0x3c, 0x3e
Edit
I'm sure there will be some issue with encoding here, but none was specified in the question.
Extra Edit
The code above will give you an IEnumerable<byte>. To get the actual byte[] you want, just call
bytes.ToArray();

Convert to byte array as this.
string source = "\x90<>";
byte[] bytes = Encoding.Default.GetBytes(source);

Related

Read and write more than 8 bit symbols

I am trying to write an Encoded file.The file has 9 to 12 bit symbols. While writing a file I guess that it is not written correctly the 9 bit symbols because I am unable to decode that file. Although when file has only 8 bit symbols in it. Everything works fine. This is the way I am writing a file
File.AppendAllText(outputFileName, WriteBackContent, ASCIIEncoding.Default);
Same goes for reading with ReadAllText function call.
What is the way to go here?
I am using ZXing library to encode my file using RS encoder.
ReedSolomonEncoder enc = new ReedSolomonEncoder(GenericGF.AZTEC_DATA_12);//if i use AZTEC_DATA_8 it works fine beacuse symbol size is 8 bit
int[] bytesAsInts = Array.ConvertAll(toBytes.ToArray(), c => (int)c);
enc.encode(bytesAsInts, parity);
byte[] bytes = bytesAsInts.Select(x => (byte)x).ToArray();
string contentWithParity = (ASCIIEncoding.Default.GetString(bytes.ToArray()));
WriteBackContent += contentWithParity;
File.AppendAllText(outputFileName, WriteBackContent, ASCIIEncoding.Default);
Like in the code I am initializing my Encoder with AZTEC_DATA_12 which means 12 bit symbol. Because RS Encoder requires int array so I am converting it to int array. And writing to file like here.But it works well with AZTEC_DATA_8 beacue of 8 bit symbol but not with AZTEC_DATA_12.
Main problem is here:
byte[] bytes = bytesAsInts.Select(x => (byte)x).ToArray();
You are basically throwing away part of the result when converting the single integers to single bytes.
If you look at the array after the call to encode(), you can see that some of the array elements have a value higher than 255, so they cannot be represented as bytes. However, in your code quoted above, you cast every single element in the integer array to byte, changing the element when it has a value greater than 255.
So to store the result of encode(), you have to convert the integer array to a byte array in a way that the values are not lost or modified.
In order to make this kind of conversion between byte arrays and integer arrays, you can use the function Buffer.BlockCopy(). An example on how to use this function is in this answer.
Use the samples from the answer and the one from the comment to the answer for both conversions: Turning a byte array to an integer array to pass to the encode() function and to turn the integer array returned from the encode() function back into a byte array.
Here are the sample codes from the linked answer:
// Convert byte array to integer array
byte[] result = new byte[intArray.Length * sizeof(int)];
Buffer.BlockCopy(intArray, 0, result, 0, result.Length);
// Convert integer array to byte array (with bugs fixed)
int bytesCount = byteArray.Length;
int intsCount = bytesCount / sizeof(int);
if (bytesCount % sizeof(int) != 0) intsCount++;
int[] result = new int[intsCount];
Buffer.BlockCopy(byteArray, 0, result, 0, byteArray.Length);
Now about storing the data into files: Do not turn the data into a string directly via Encoding.GetString(). Not all bit sequences are valid representations of characters in any given character set. So, converting a random sequence of random bytes into a string will sometimes fail.
Instead, either store/read the byte array directly into a file via File.WriteAllBytes() / File.ReadAllBytes() or use Convert.ToBase64() and Convert.FromBase64() to work with a base64 encoded string representation of the byte array.
Combined here is some sample code:
ReedSolomonEncoder enc = new ReedSolomonEncoder(GenericGF.AZTEC_DATA_12);//if i use AZTEC_DATA_8 it works fine beacuse symbol size is 8 bit
int[] bytesAsInts = Array.ConvertAll(toBytes.ToArray(), c => (int)c);
enc.encode(bytesAsInts, parity);
// Turn int array to byte array without loosing value
byte[] bytes = new byte[bytesAsInts.Length * sizeof(int)];
Buffer.BlockCopy(bytesAsInts, 0, bytes, 0, bytes.Length);
// Write to file
File.WriteAllBytes(outputFileName, bytes);
// Read from file
bytes = File.ReadAllBytes(outputFileName);
// Turn byte array to int array
int bytesCount = bytes.Length * 40;
int intsCount = bytesCount / sizeof(int);
if (bytesCount % sizeof(int) != 0) intsCount++;
int[] dataAsInts = new int[intsCount];
Buffer.BlockCopy(bytes, 0, dataAsInts, 0, bytes.Length);
// Decoding
ReedSolomonDecoder dec = new ReedSolomonDecoder(GenericGF.AZTEC_DATA_12);
dec.decode(dataAsInts, parity);

How to write hex values in byte array?

I have a hex value of 0x1047F71 and I want to put in byte array of 4 bytes. Is this the right way to do it:
byte[] sync_welcome_sent = new byte[4] { 0x10, 0x47, 0xF7, 0x01 };
or
byte[] sync_welcome_sent = new byte[4] { 0x01, 0x04, 0x7F, 0x71 };
I would appreciate any help.
If you want to be compatible with Intel little-endian, the answer is "None of the above", because the answer would be "71h, 7fh, 04h, 01h".
For big-endian, the second answer above is correct: "01h, 04h, 7fh, 71h".
You can get the bytes with the following code:
uint test = 0x1047F71;
var bytes = BitConverter.GetBytes(test);
If you want big-endian, you can just reverse the bytes using Linq like so:
var bytes = BitConverter.GetBytes(test).Reverse();
However, if you are running the code on a Big Endian system, reversing the bytes will not be necessary, since BitConverter.GetBytes()will return them as big endian on a big endian system.
Therefore you should write the code as follows:
uint test = 0x1047F71;
var bytes = BitConverter.GetBytes(test);
if (BitConverter.IsLittleEndian)
bytes = bytes.Reverse().ToArray();
// now bytes[] are big-endian no matter what system the code is running on.

How can I write bytes to a file but break when the byte is equal to 0x00 or null?

How can I write a byte array to a file but then break when the byte that is about to be written is equal to 0x00 or null?
I've tried to turn the bytes into a string and trim but that does not work.
message = new byte[4096];
clientStream.Read(message, 0, 4096);
clientStream.Flush();
File.WriteAllText(AUTH_KEY"/email.txt",encoder.GetString(message).Trim());
Find the first index of 0x00 and then block write everything before it.
You can copy everything before the first 0x00 into a new array and then call
File.WriteAllBytes( string path, byte[] bytes)

It is posible to add string with byte? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
How to append string and byte array?
String array="$MT!BOOTLOADER";
Byte[] hexdecimal={0x01,0x05,0x0036};
You probably want to do something low level, so in the end you won't need a string but a byte[], so:
string array="$MT!BOOTLOADER";
byte[] hexdecimal={0x01,0x05,0x36};
byte[] bytesOrig = Encoding.ASCII.GetBytes(array);
byte[] bytesFinal = bytesOrig;
Array.Resize(ref bytesFinal, bytesFinal.Length + hexdecimal.Length);
Array.Copy(hexdecimal, 0, bytesFinal, bytesOrig.Length, hexdecimal.Length);
// bytesFinal contains all the bytes
I'm using Encoding.ASCII because your signature is ASCII (and normally signatures are ASCII)
equivalent code, but little different (we preallocate the array with the right size, by doing two calls to Encoding.ASCII methods)
string array="$MT!BOOTLOADER";
byte[] hexdecimal={0x01,0x05,0x36};
int count = Encoding.ASCII.GetByteCount(array);
byte[] bytes = new byte[count + hexdecimal.Length];
Encoding.ASCII.GetBytes(array, 0, array.Length, bytes, 0);
Array.Copy(hexdecimal, 0, bytes, count, hexdecimal.Length);
// bytes contains all the bytes
Use this function for converting string to byte and byte to string.
static byte[] GetBytes(string str)
{
byte[] bytes = new byte[str.Length * sizeof(char)];
System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
static string GetString(byte[] bytes)
{
char[] chars = new char[bytes.Length / sizeof(char)];
System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
return new string(chars);
}

BitConverter.ToInt32 to convert 2 bytes

I am using BitConverter.ToInt32 to convert a Byte array into int.
I have only two bytes [0][26], but the function needs 4 bytes, so I have to add two 0 bytes to the front of the existing bytes.
What is the quickest method.
Thank you.
You should probably do (int)BitConverter.ToInt16(..) instead. ToInt16 is made to read two bytes into a short. Then you simply convert that to an int with the cast.
You should call `BitConverter.ToInt16, which only reads two bytes.
short is implicitly convertible to int.
Array.Copy. Here is some code:
byte[] arr = new byte[] { 0x12, 0x34 };
byte[] done = new byte[4];
Array.Copy(arr, 0, done, 2, 2); // http://msdn.microsoft.com/en-us/library/z50k9bft.aspx
int myInt = BitConverter.ToInt32(done); // 0x00000026
However, a call to `BitConverter.ToInt16(byte[]) seems like a better idea, then just save it to an int:
int myInt = BitConverter.ToInt16(...);
Keep in mind endianess however. On little endian machines, { 0x00 0x02 } is actually 512, not 2 (0x0002 is still 2, regardless of endianness).

Categories

Resources