C# ByteArray to string conversion and back - c#

I have a uint value that I need to represent as a ByteArray and the convert in a string.
When I convert back the string to a byte array I found different values.
I'm using standard ASCII converter so I don't understand why I'm getting different values.
To be more clear this is what I'm doing:
byte[] bArray = BitConverter.GetBytes((uint)49694);
string test = System.Text.Encoding.ASCII.GetString(bArray);
byte[] result = Encoding.ASCII.GetBytes(test);
The bytearray result is different from the first one:
bArray ->
[0x00000000]: 0x1e
[0x00000001]: 0xc2
[0x00000002]: 0x00
[0x00000003]: 0x00
result ->
[0x00000000]: 0x1e
[0x00000001]: 0x3f
[0x00000002]: 0x00
[0x00000003]: 0x00
Notice that the byte 1 is different in the two arrays.
Thanks for your support.
Regards

string test = System.Text.Encoding.ASCII.GetString(bArray);
byte[] result = Encoding.ASCII.GetBytes(test);
Because raw data is not ASCII. Encoding.GetString is only meaningful if the data you are decoding is text data in that encoding. Anything else: you corrupt it. If you want to store a byte[] as a string, then base-n is necessary - typically base-64 because a: it is conveniently available (Convert.{To|From}Base64String), and b: you can fit it into ASCII, so you rarely hit code-page / encoding issues. For example:
byte[] bArray = BitConverter.GetBytes((uint)49694);
string test = Convert.ToBase64String(bArray); // "HsIAAA=="
byte[] result = Convert.FromBase64String(test);

Because c2 is not a valid ASCII char and it is replaced with '?'(3f)
Converting any byte array to string using SomeEncoding.GetString() is not a safe method as #activwerx suggested in comments. Instead use Convert.FromBase64String, Convert.ToBase64String

Related

C# String to Byte Array (With preset string format)

I am working a problem in C# and I am having issues with converting my string of multiple hex values to a byte[].
string word = "\xCD\x01\xEF\xD7\x30";
(\x starts each new value, so I have: CD 01 EF D7 30)
This is my first time asking a question here, so please let me know if you need anything extra from me.
More information on the project:
I need to be able to change both
"apple" and "\xCD\x01\xEF\xD7\x30" to a byte array.
For the normal string "apple" I use
byte[] data = Encoding.ASCII.GetBytes(word);
this does not seem to be working with "\xCD\x01\xEF\xD7\x30" I am getting the values
63, 1, 63, 63, 48
Ok... You were trying to directly "downcast"/"upcast" char <-> byte (where char is the C# char that is 16 bits long, and byte is 8 bits long).
There are various ways to do it. The simplest (probably not the more performant) is to use the iso-8859-1 encoding that "maps" the byte values 0-255 to the unicode codes 0-255 (and return).
Encoding enc = Encoding.GetEncoding("iso-8859-1");
string str = "apple";
byte[] bytes = enc.GetBytes(str);
string str2 = enc.GetString(bytes);
You can even do a little LINQ:
string str = "apple";
// This is "bad" if the string contains codepoints > 255
byte[] bytes = str.Select(x => (byte)x).ToArray();
// This is always safe, because by definition any value of a byte
// is a legal unicode character
string str2 = string.Concat(bytes.Select(x => (char)x));

Convert C# string to C char array

I am sending a string from C# to C via sockets:
write 5000 100
In C, I split the received string using spaces.
char **params = str_split(buffer, ' ');
And then access the 3rd parameter, and convert 100 into C char. However, I need to be able to send an array of chars from C# (1 byte each) so that I can use them in C.
For instance, let's say I need to send the following string:
write 5000 <byte[] { 0x01, 0x20, 0x45 }>
Of course, the byte array needs to be transformed into string characters in C# that can be sent via StreamWriter. StreamWriter accepts array of chars which are 2 bytes each, but I need 1 byte.
How can this be accomplished?
In C, char is of 1 byte size. Thus, to accommodate them from C#, you will need to send byte.
And it seems like you need two different inputs for your problem:
C#
string textFront = "write 5000"; //input 1
byte[] bytes = new byte[] { 0x01, 0x20, 0x45 }; //input 2
And then to send them together, I would rather use Stream which allows you to send byte[]. Thus, we only need to (1) Change the textFront into byte[], (2) concat textFront with bytes, and lastly (3) send combined variable as byte[].
byte[] frontBytes = Encoding.ASCII.GetBytes(textFront); // no (1)
byte[] combined = new byte[frontBytes.Length + bytes.Length];
frontBytes.CopyTo(combined, 0);
bytes.CopyTo(combined, frontBytes.Length); //no (2)
Stream stream = new StreamWriter(); //no (3)
stream.Write(combined, 0, combined.Length);
I don't quite understand your question, is it what you are looking for?
byte[] bytes = Encoding.UTF8.GetBytes("your string");
and vice versa
string text = Encoding.UTF8.GetString(bytes);
The StreamWriter constructor may receive a Encoding parameter. Maybe that's what you want.
var sw = new StreamWriter(your_stream, Encoding.ASCII);
sw.Write("something");
There is also the BinaryWriter class that can write strings and byte[].
var bw = new BinaryWriter(output_stream, Encoding.ASCII);
bw.Write("something");
bw.Write(new byte[] { 0x01, 0x20, 0x45 });

Bit Array to String and back to Bit Array

Possible Duplicate Converting byte array to string and back again in C#
I am using Huffman Coding for compression and decompression of some text from here
The code in there builds a huffman tree to use it for encoding and decoding. Everything works fine when I use the code directly.
For my situation, i need to get the compressed content, store it and decompress it when ever need.
The output from the encoder and the input to the decoder are BitArray.
When I tried convert this BitArray to String and back to BitArray and decode it using the following code, I get a weird answer.
Tree huffmanTree = new Tree();
huffmanTree.Build(input);
string input = Console.ReadLine();
BitArray encoded = huffmanTree.Encode(input);
// Print the bits
Console.Write("Encoded Bits: ");
foreach (bool bit in encoded)
{
Console.Write((bit ? 1 : 0) + "");
}
Console.WriteLine();
// Convert the bit array to bytes
Byte[] e = new Byte[(encoded.Length / 8 + (encoded.Length % 8 == 0 ? 0 : 1))];
encoded.CopyTo(e, 0);
// Convert the bytes to string
string output = Encoding.UTF8.GetString(e);
// Convert string back to bytes
e = new Byte[d.Length];
e = Encoding.UTF8.GetBytes(d);
// Convert bytes back to bit array
BitArray todecode = new BitArray(e);
string decoded = huffmanTree.Decode(todecode);
Console.WriteLine("Decoded: " + decoded);
Console.ReadLine();
The Output of Original code from the tutorial is:
The Output of My Code is:
Where am I wrong friends? Help me, Thanks in advance.
You cannot stuff arbitrary bytes into a string. That concept is just undefined. Conversions happen using Encoding.
string output = Encoding.UTF8.GetString(e);
e is just binary garbage at this point, it is not a UTF8 string. So calling UTF8 methods on it does not make sense.
Solution: Don't convert and back-convert to/from string. This does not round-trip. Why are you doing that in the first place? If you need a string use a round-trippable format like base-64 or base-85.
I'm pretty sure Encoding doesn't roundtrip - that is you can't encode an arbitrary sequence of bytes to a string, and then use the same Encoding to get bytes back and always expect them to be the same.
If you want to be able to roundtrip from your raw bytes to string and back to the same raw bytes, you'd need to use base64 encoding e.g.
http://blogs.microsoft.co.il/blogs/mneiter/archive/2009/03/22/how-to-encoding-and-decoding-base64-strings-in-c.aspx

How to save byte[] in c# application settings

I am trying to save a byte array (byte[]) in c# application settings that is returned by Object List View.
Can anyone give me a solution on how to save byte array in c# application settings?
or some trick on how to convert byte[] to something like a string then store, then retrieve and again convert it to byte array and give it back to object list view.
One of the most common ways to make a string from an array of bytes is encoding them in Base-64:
string encoded = System.Convert.ToBase64String(toEncodeAsBytes);
Use
byte[] bytes = System.Convert.FromBase64String(encoded);
to get your bytes back.
The canonical way to do this is to convert the byte[] to a string via base64 and the other way round.
By Different way you can convert Byte array to string and string to byte array. Like this :
1)
string asciiString = ASCIIEncoding.ASCII.GetString(byteArray);
byte[] byte = ASCIIEncoding.ASCII.GetBytes(asciiString);
2)
string base64String = System.Convert.ToBase64String(byteArray);
byte[] byte = System.Convert.FromBase64String(base64String);
3)
string utf8String = System.Text.Encoding.UTF8.GetString(byteArray);
byte[] byte = System.Text.Encoding.UTF8.GetBytes(utf8String);
you can also use System.Text.Encoding.BigEndianUnicode, System.Text.Encoding.Unicode, and System.Text.Encoding.UTF32 for converting Byte Array to string and string to Byte Array.
Hope, It should help you.

Convert a binary number to ascii characters

I am reading information from a device and it's returning data to me in integer format and I need to convert this to ASCII characters using C#.
The following is an example of the data I have to convert. I receive the integer value 26990 back from my device and I need to convert that to ASCII. I just happen to know that for this value, the desired result would be "ni".
I know that the integer value 26990 is equal to 696e in hex, and 110100101101110 in binary, but would like to know how to do the conversion as I can't work it out for myself.
Can anyone help please?
Many thanks,
Karl
int i = 26990;
char c1 = (char)(i & 0xff);
char c2 = (char)(i >> 8);
Console.WriteLine("{0}{1}", c1, c2);
Use BitConverter and Encoding to perform the conversion:
class Program
{
public static void Main()
{
int d = 26990;
byte[] bytes = BitConverter.GetBytes(d);
string s = System.Text.Encoding.ASCII.GetString(bytes);
// note that s will contain extra NULLs here so..
s = s.TrimEnd('\0');
}
}
If the device is sending bytes you can use something like this:
byte[] bytes = new byte[] { 0x69, 0x6e };
string text = System.Text.Encoding.ASCII.GetString(bytes);
Otherwise, if the device is sending integers you can use something like this:
byte[] bytes = BitConverter.GetBytes(26990);
string text = System.Text.Encoding.ASCII.GetString(bytes, 0, 2);
In either case, text will contain "ni" after that executes. Note that in the latter you may have to deal with endianness issues.
Further reference:
Encoding class
Encoding.ASCII property
Encoding.GetString method overloads

Categories

Resources