Convert a byte[] to its string representation in binary - c#

I need to convert a Byte[] to a string which contain a binary number sequence. I cannot use Encoding because it just encodes bytes into characters!
For example, having this array:
new byte[] { 254, 1 };
I want this output:
"1111111000000001"

You can convert any numeric integer primitive to its binary representation as a string with Convert.ToString. Doing this for each byte in your array and concatenating the results is very easy with LINQ:
var input = new byte[] { 254 }; // put as many bytes as you want in here
var result = string.Concat(input.Select(b => Convert.ToString(b, 2)));
Update:
The code above will not produce a result having exactly 8 characters per input byte, and this will make it impossible to know what the input was just by looking at the result. To get exactly 8 chars per byte, a small change is needed:
var result = string.Concat(input.Select(b => Convert.ToString(b, 2).PadLeft(8, '0')));

string StringIWant = BitConverter.ToString(byteData);
But i suggest work with Encoding..
string System.Text.Encoding.UTF8.GetString(byte[])
EDIT: For like 10101011010
From #Quintin Robinson's answer;
StringBuilder sb = new StringBuilder();
foreach (byte b in myByteArray)
sb.Append(b.ToString("X2"));
string hexString = sb.ToString();

Perhaps you can use the BitArray class to accomplish what you are looking for? They have some sample code in the reference which should be pretty easy to convert to what you are looking for.

Will BitConverter.ToString work for you?

byte[] bList = { 0, 1, 2, 3, 4, 5 };
string s1 = BitConverter.ToString(bList);
string s2 = "";
foreach (byte b in bList)
{
s2 += b.ToString();
}
in this case s1 ="01-02-03-04-05"
and s2= "012345"
I don't really get what are you trying to achieve.

Related

Better way of generating an alphanumeric 50 char long GUID

I am generating 2 GUIDs and taking the first 50 chars from them. What is the better way of doing this -
string tr1 = string.Join("", Guid.NewGuid().ToString("n"));
string tr2 = string.Join("", Guid.NewGuid().ToString("n"));
string full = ( tr1 + "#" + tr2).Left(50);
This isn't what you asked for, but I think it's what you want:
using System.Security.Cryptography;
public static string Get50RandomHexNybls()
{
var bytes = new byte[25];
var rand = new RNGCryptoServiceProvider();
rand.GetBytes(bytes);
return BitConverter.ToString(bytes).Replace("-", string.Empty);
}
The result looks like:
B7EB8387438D55CAEC2C9D4EE73E8B99BB146EEDA4F8A9CB48
with a different result each time. If you don't like how I converted the bytes to a hex string, take a look at "How do you convert a byte array to a hexadecimal string, and vice versa"

Base64 Encoding Javascript to C#

I am trying to port some Javascript to C# and I'm having a bit of trouble. The javascript I am porting calls this
var binary = out.map(function (c) {
return String.fromCharCode(c);
}).join("");
return btoa(binary);
out is an array of numbers. I understand that it is taking the numbers and using fromCharCode to add characters to a string. At first I wasn't sure if my C# equivalent of btoa was working correctly, but the only characters I'm having issues with are the first 6 or 8. My encoded string outputs the same except for the first few characters.
At first in C# I was doing this
String binary = "";
foreach(int val in output){
binary += ((char)val);
}
And then I tried
foreach(int val in output){
System.Text.ASCIIEncoding convertor = new System.Text.ASCIIEncoding();
char o = convertor.GetChars(new byte[] { (byte)val })[0];
binary += o;
}
Both work fine on the later characters of the String but not the start. I've researched but I don't know what I'm missing.
My array of numbers is as follows: { 10, 135, 3, 10, 182, ....}
I know the 10s are newline characters, the 3 is end of text, the 182 is ¶, but what's confusing me is that the 135 should be the double dagger ‡. The Javascript does not show it when I print the string.
So what ends up happening is when the String is converted to Base64 my string looks like Cj8DCj8CRFF.... while the Javascript String looks like CocDCrYCRFF.... The rest of the strings are the same and the int arrays used are identical.
Any ideas?
It's important to understand that binary data does not always represent valid text in a given encoding, and that some encodings have variable numbers of bytes to represent different characters. In short: binary data and text are not the same at all, and you can only convert between the two in some cases and by following clear, accurate rules. Treating them incorrectly will cause pain.
That said, if you have a list of ints, that are always within the range 0-255, that should become a base64 string, here is a way to do it:
var output = new[] { 0, 1, 2, 68, 69, 70, 254, 255 };
var binary = new List<byte>();
foreach(int val in output){
binary.Add((byte)val);
}
var result = Convert.ToBase64String(binary.ToArray());
If you have text that should be encoded as a base64 string...generally I'd recommend UTF8 encoding, unless you need it to match the JS's implementation.
var str = "Hello, world!";
var result = Convert.ToBase64String(Encoding.UTF8.GetBytes(str));
The encoding that JS uses appears to be the same as casting between byte and char (chars > 255 are invalid), which isn't one of the standard Encodings available.
Here's how you might combine raw numbers and strings, then convert that to base64.
checked // ensures that values outside of byte's range do not fail silently
{
var output = new int[] { 10, 135, 3, 10, 182 };
var binary = output.Select(x => (byte)x)
.Concat("Hello, world".Select(c => (byte)c)).ToArray();
var result = Convert.ToBase64String(binary);
}

C# ByteString to ASCII String

I am looking for a smart way to convert a string of hex-byte-values into a string of 'real text' (ASCII Characters).
For example I have the word "Hello" written in Hexadecimal ASCII: 48 45 4C 4C 4F. And using some method I want to receive the ASCII text of it (in this case "Hello").
// I have this string (example: "Hello") and want to convert it to "Hello".
string strHexa = "48454C4C4F";
// I want to convert the strHexa to an ASCII string.
string strResult = ConvertToASCII(strHexa);
I am sure there is a framework method. If this is not the case of course I could implement my own method.
Thanks!
var str = Encoding.UTF8.GetString(SoapHexBinary.Parse("48454C4C4F").Value); //HELLO
PS: SoapHexBinary is in System.Runtime.Remoting.Metadata.W3cXsd2001 namespace
I am sure there is a framework method.
A a single framework method: No.
However the second part of this: converting a byte array containing ASCII encoded text into a .NET string (which is UTF-16 encoded Unicode) does exist: System.Text.ASCIIEncoding and specifically the method GetString:
string result = ASCIIEncoding.GetString(byteArray);
The First part is easy enough to do yourself: take two hex digits at a time, parse as hex and cast to a byte to store in the array. Seomthing like:
byte[] HexStringToByteArray(string input) {
Debug.Assert(input.Length % 2 == 0, "Must have two digits per byte");
var res = new byte[input.Length/2];
for (var i = 0; i < input.Length/2; i++) {
var h = input.Substring(i*2, 2);
res[i] = Convert.ToByte(h, 16);
}
return res;
}
Edit: Note: L.B.'s answer identifies a method in .NET that will do the first part more easily: this is a better approach that writing it yourself (while in a, perhaps, obscure namespace it is implemented in mscorlib rather than needing an additional reference).
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hexStr.Length; i += 2)
{
string hs = hexStr.Substring(i, 2);
sb.Append(Convert.ToByte(hs, 16));
}

Correct Encoding style for convert bytes[] to string

I am trying to convert a byte array to a string, all i need is to simply convert the number in byteArray to string Foreg. "12459865..."
I am trying to do this with this:
fileInString = Encoding.UTF8.GetString(fileInBytes, 0, fileInBytes.Length);
fileInBytes looks like this: 1212549878563212450045....
But resultant fileInString looks like this ID3\0\0\0\0JTENC\0\0\0#\0\0WXXX\0... and alot of weird characters.
I tried different Encoding styles including default but all insert some weird characters into it.
The only option I have is to loop and cast each member into the string
while (currbyte != -1)
{
currbyte = fileStream.ReadByte();
//fileInBytes[i++] = (byte)currbyte;
fileInString += currbyte.ToString();
progressBar1.Value = i++;
}
But this is TOO slow. Please tell me how can I convert by byte array into string using Encoding.....GetString
If you want to encode a byte[] as a string, base64 encoding with Convert's ToBase64String and FromBase64String methods is a good way to do this:
string fileInString = Convert.ToBase64String(fileInBytes);
byte[] asBytesAgain = Convert.FromBase64String(fileInString);
Your encoding using fileInString += currbyte.ToString(); appears to be an ambiguous base 10 encoding. E.g. from what I can tell, the arrays with values { 1, 10, 255 } and { 110, 255 } would be encoded the same: "110255", and so cannot be unambiguously changed back into a byte[].
There is no encoding that can achieve what you want.
You need to loop through the bytes as you do.
To make it faster, use a StringBuilder and don't update the ProgressBar too often:
var builder = new StringBuilder();
for (var i = 0; i < fileStream.Length; i++)
{
builder.Append(fileStream.ReadByte().ToString());
if (i % 1000 == 0) //update the ProgressBar every 1000 bytes for example
{
progressBar.Value = i;
}
}
var result = builder.ToString();
Well, since you are referring to a byte ARRAY, fileInBytes really can't look like '1212549878563212450045', but rather like this:
{byte[22]}
[0]: 1
[1]: 2
etc.
If that is indeed the case you should be able fileInString using StringBuilder as follows:
StringBuilder sb = new StringBuilder();
foreach (var b in fileInBytes)
{
sb.Append(b.ToString());
}
fileInString = sb.ToString();

How can i convert a string of characters into binary string and back again?

I need to convert a string into it's binary equivilent and keep it in a string. Then return it back into it's ASCII equivalent.
You can encode a string into a byte-wise representation by using an Encoding, e.g. UTF-8:
var str = "Out of cheese error";
var bytes = Encoding.UTF8.GetBytes(str);
To get back a .NET string object:
var strAgain = Encoding.UTF8.GetString(bytes);
// str == strAgain
You seem to want the representation as a series of '1' and '0' characters; I'm not sure why you do, but that's possible too:
var binStr = string.Join("", bytes.Select(b => Convert.ToString(b, 2)));
Encodings take an abstract string (in the sense that they're an opaque representation of a series of Unicode code points), and map them into a concrete series of bytes. The bytes are meaningless (again, because they're opaque) without the encoding. But, with the encoding, they can be turned back into a string.
You seem to be mixing up "ASCII" with strings; ASCII is simply an encoding that deals only with code-points up to 128. If you have a string containing an 'é', for example, it has no ASCII representation, and so most definitely cannot be represented using a series of ASCII bytes, even though it can exist peacefully in a .NET string object.
See this article by Joel Spolsky for further reading.
You can use these functions for converting to binary and restore it back :
public static string BinaryToString(string data)
{
List<Byte> byteList = new List<Byte>();
for (int i = 0; i < data.Length; i += 8)
{
byteList.Add(Convert.ToByte(data.Substring(i, 8), 2));
}
return Encoding.ASCII.GetString(byteList.ToArray());
}
and for converting string to binary :
public static string StringToBinary(string data)
{
StringBuilder sb = new StringBuilder();
foreach (char c in data.ToCharArray())
{
sb.Append(Convert.ToString(c, 2).PadLeft(8, '0'));
}
return sb.ToString();
}
Hope Helps You.
First convert the string into bytes, as described in my comment and in Cameron's answer; then iterate, convert each byte into an 8-digit binary number (possibly with Convert.ToString, padding appropriately), then concatenate. For the reverse direction, split by 8 characters, run through Convert.ToInt16, build up a byte array, then convert back to a string with GetString.

Categories

Resources