String representation of byte array - c#

I have a string that represents a byte
string s = "\x00af";
I write this string to a file so the file contains the literal "\x00af" and not the byte it represents, later I read this string from the file, how can I now treat this string as byte again (and not the literal)?
Here is a sample code:
public static void StringAndBytes()
{
string s = "\x00af";
byte[] b = Encoding.ASCII.GetBytes(s);
// Length would be 1
Console.WriteLine(b.Length);
// Write this to a file as literal
StreamWriter sw = new StreamWriter("c:\\temp\\MyTry.txt");
sw.WriteLine("\\x00af");
sw.Close();
// Read it from the file
StreamReader sr = new StreamReader("c:\\temp\\MyTry.txt");
s = sr.ReadLine();
sr.Close();
// Get the bytes and Length would be 6, as it treat the string as string
// and not the byte it represents
b = Encoding.ASCII.GetBytes(s);
Console.WriteLine(b.Length);
}
Any idea on how I convert the string from being a text to the string representing a byte? Thx!

Is it a requirement for the file content to have the string literal? If no, then you might want to write the byte[] b array directly to the file. That way when you read it, it is exactly, what you wrote.
byte[] b = Encoding.UTF32.GetBytes(s);
File.WriteAllBytes ("c:\\temp\\MyTry.txt", b);
b = File.ReadAllBytes ("c:\\temp\\MyTry.txt");
s = Encoding.UTF32.GetString (b);
If you need the file content to have the string literal, while being able to convert it to the original text written, you will have to choose the right encoding. I believe UTF32 to be the best.
b = new byte[4];
b[0] = Byte.Parse(s.Substring(2), System.Globalization.NumberStyles.AllowHexSpecifier);
string v = Encoding.UTF32.GetString(b);
string w = "\x00af";
if (v != w)
MessageBox.Show("Diff [" + w + "] = [" + v + "] ");
else
MessageBox.Show("Same");

Not sure if I understand the question correctly, but you're not writing the string s to the file. You have an extra \ in your WriteLine statement! WriteLine("\\x00af") writes the characters \, x, 0, 0, a and f, since the first \ acts as an escape to the second one ...
Did you mean
sw.WriteLine("\x00af");
or
sw.WriteLine(s);
instead? This works as expected in my tests.

Use the Encoding.ASCII.GetString(byte[]) method. It is also available from all the others encoding. Make sure you always use the same encoding to decode the byte[] as you used to encode it or you won't get the same value every time.
Here's an example.

Just parse a string representing each byte:
Byte b = Byte.Parse(s);

Related

How to convert a byteArray to Binary Value in c#?

I initilaly have a string which is converted to byteArray.
Then I convert this byteArray to HEX as shown below in my code.
Then I further need to convert this to a binary value.
string ID = "A0101185K";
byte[] ba = Encoding.Default.GetBytes(IC);
var hexString= BitConverter.ToString(ba).Replace("-", "");
You can convert byte to string in that way
static string ToBinary(byte b) => Convert.ToString(b, 2).PadLeft(8, '0');
and use it in your program like this
string MESSAGE = "A0101185K";
byte[] bytes = Encoding.Default.GetBytes(MESSAGE);
var binaries = string.Concat(bytes.Select(ToBinary));
I hope that helps you. But of course you didn't tell how you want to store your result, so maybe this is not the right answer.

String value system.byte[] while coverting Base64 value to string in c#

I have two LDIF files from where I am reading values and using it for comparsion using c#
One of the attribute: value in LDIF is a base64 value, need to convert it in UTF-8 format
displayName:: Rmlyc3ROYW1lTGFzdE5hbWU=
So I thought of using string -> byte[], but I am not able to use the above displayName value as string
byte[] newbytes = Convert.FromBase64String(displayname);
string displaynamereadable = Encoding.UTF8.GetString(newbytes);
In my C# code, I am doing this to retrieve the values from the ldif file
for(Entry entry ldif.ReadEntry() ) //reads value from ldif for particular user's
{
foreach(Attr attr in entry) //here attr gives attributes of a particular user
{
if(attr.Name.Equals("displayName"))
{
string attVal = attr.Value[0].ToString(); //here the value of String attVal is system.Byte[], so not able to use it in the next line
byte[] newbytes = Convert.FromBase64String(attVal); //here it throws an error mentioned below
string displaynamereadable = Encoding.UTF8.GetString(attVal);
}
}
}
Error:
The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.
I am trying to user attVal as String so that I can get the encoded UTf-8 value but its throwing an error.
I tried to use BinaryFormatter and MemoryStream as well, it worked but it inserted so many new chars with the original value.
Snapshot of BinaryFormatter:
object obj = attr.Value[0];
byte[] bytes = null;
BinaryFormatter bf = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream())
{
bf.Serialize(ms, obj);
bytes = (ms.ToArray());
}
string d = Encoding.UTF8.GetString(bytes);
So the result after encoding should be: "FirstNameLastName"
But it gives "\u0002 \u004 \u004 ...................FirstNameLastName\v"
Thanks,
Base64 was designed to send binary data through transfer channels that only support plain text, and as a result, Base64 is always ASCII text. So if attr.Value[0] is a byte array, just interpret those bytes as string using ASCII encoding:
String attVal = Encoding.ASCII.GetString(attr.Value[0] as Byte[]);
Byte[] newbytes = Convert.FromBase64String(attVal);
String displaynamereadable = Encoding.UTF8.GetString(newbytes);
Also note, your code above was feeding attVal into that final line rather than newbytes.

this base64 string is not getting decoded

I have this image represented as base64 string which I have pasted over here:
https://paste.ubuntu.com/23343680/
there is an image inside it. I am calling a
Convert.FromBase64String
and it gives me
{"Invalid length for a Base-64 char array or string."}
Now I have used this website http://codebeautify.org/base64-to-image-converter to paste the same string and it renders the image in the data just fine.
What is it that I am doing wrong here, I need to get a byte[] which I will make the image from but I cant.
thanks.
You have to append = until the length is divisible by 4. Only that is a valid base64 string.
This code will do:
string s = "yourVeryLongBase64String";
if ((s.Length % 4) > 0)
{
int diff = 4 - (s.Length % 4);
s = s.PadRight(s.Length + diff, '=');
}
byte[] b = Convert.FromBase64String(s);
string str = "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAIBAQEBAQIBAQECAgICAgQDAgICAgUEBAMEBgUGBgYFBgYGBwkIBgcJBwYGCAsICQoKCgoKBggLDAsKDAkKCgr/2wBDAQICAgICAgUDAwUKBwYHCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgr/wAARCAHgAoADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDk6KKKACiiigAooooA/EuiiigAooooAKKKKACiiigD9tKKKKACiiigAooooAKKKKAPxLooooAKKKKACiiigAooooA/bSiiigAooooAKKKKACiiigD8S6KKKACiiigAooooAKKKKAP20ooooAKKKKACiiigAooooA/EuiiigAooooAKKKKACiiigD9tKKKKACiiigAooooAKKKKAPxLooooAKKKKACiiigAooooA/bSiiigAooooAKKKKACiiigD8S6KKKACiiigAooooAKKKKAP20ooooAKKKKACiiigAooooA/EuiiigAooooAKKKKACiiigD9tKKKKACiiigAooooAKKKKAPxLooooAKKKKACiiigAooooA/bSiiigAooooAKKKKACiiigD8S6KKKACiiigAooooAKKKKAP20ooooAKKKKACiiigAooooA/EuiiigAooooAKKKKACiiigD9tKKKKAPEv+HjP7Fn/AEWf/wAt/UP/AJHo/wCHjP7Fn/RZ/wDy39Q/+R6/LiigD9R/+HjP7Fn/AEWf/wAt/UP/AJHo/wCHjP7Fn/RZ/wDy39Q/+R6/LiigD9R/+HjP7Fn/AEWf/wAt/UP/AJHo/wCHjP7Fn/RZ/wDy39Q/+R6/LiigD23/AIdy/tp/9EZ/8uDT/wD5Io/4dy/tp/8ARGf/AC4NP/8Akiv1HooA/Lj/AIdy/tp/9EZ/8uDT/wD5Io/4dy/tp/8ARGf/AC4NP/8Akiv1HooA/Lj/AIdy/tp/9EZ/8uDT/wD5Io/4dy/tp/8ARGf/AC4NP/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iigAooooAKKKKACiiigD8S6KKKACiiigAooooAKKKKAP20ooooAKKKKACiiigAooooA/EuiiigAooooAKKKKACiiigD9tKKKKACiiigAooooAKKKKAPxLooooAKKKKACiiigAooooA===";
byte[] arr = Convert.FromBase64String(str);
Add == at the end of string. it will work. the input you are passing is not valid base64 value

get dsa signature value in octect string

I am trying to read the octect string value of attribute dsa-signature. I got the field from default naming context properties. But its in byte array, when I try to convert it into a string it give wrong output.
Does anyone knows how to do correct octect converion?
DirectoryEntry entry = new DirectoryEntry("LDAP://DC=cobra,DC=net");
PropertyValueCollection propCol = entry.Properties["dSASignature"];
Console.WriteLine(propCol.PropertyName + " : " + propCol.Value);
System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
string str = enc.GetString((System.Byte[])propCol.Value);
Console.WriteLine("value : " + str);
Thanks in advance
But its in byte array, when I try to convert it into a string it give wrong output.
It's a byte array. Just an arbitrary sequence of bytes. It's not UTF-8-encoded text, which is what you're treating it as.
If you want to display the bytes formatted as hex, you can use:
byte[] data = (byte[]) propCol.Value;
string hex = BitConverter.ToString(data);
If you need to transfer it more efficiently but as text, you could use base64... but ideally you should treat it as a byte array for as long as possible, given that fundamentally it's just binary data.

Converting a Byte Array into a delimited string

I´m trying to convert a byte array to a delimited by comma string. I just want the values of de bytes into a string so I cand send a string to another pc via TCP.
This is the code that i´m running now and it´s working but it´s too slow (the byte array has 50000 elements). Do you have any better idea?.
Thanks.
byte[] bytes = (byte[])dt.Rows[0]["LNL_BLOB"];
string foto="";
foreach (byte b in bytes)
{
foto = foto + "," + b.ToString();
}
Use StringBuilder when doing lots of string operations.
In this special case, you can also use string.Join:
string foto = string.Join(",", bytes);
Well, you're allocating 100000 strings (half from the ToString() calls, half for the intermediate strings). Have you never heard about the dangers of string concatenation, and the purpose of StringBuilder?
E.g.
byte[] bytes = (byte[])dt.Rows[0]["LNL_BLOB"];
System.Text.StringBuilder foto=new System.Text.StringBuilder();
foreach (byte b in bytes)
{
foto.AppendFormat(",{0}",b);
}
return foto.ToString(); /* Or however you're using your string now */
You could use Convert.ToBase64String rather than iterating through the bytes yourself.
byte[] data = // whatever you do to get the bytes
string sData = Convert.ToBase64String(data);
Here is the method documentation.
When you wanted to get your byte array back from the string, simply use the Convert.FromBase64String ala
byte[] imageData = Convert.FromBase64String(sData);
Use a StringBuilder it is more efficient for concat on strings.
byte[] bytes = (byte[])dt.Rows[0]["LNL_BLOB"];
StringBuilder foto = new StringBuilder();
for(int i = 0; i < bytes.Length; i++) {
foto.Append(bytes[i].ToString());
if (i != (bytes.Length - 1)) foto.Append(",");
}
You can parallelize the loop and process different areas of the array in parallel and reassemble the results. And, as others have mentioned, use StringBuilder.

Categories