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();
Related
I have one column in DB containing UTF16 string and I want to convert the UTF16 string into normal text. How to achieve this in c# ?
For example :
Source : 0645 0631 062D 0628 0627 0020 0627 0644 0639 0627 0644 0645
Convert : مرحبا العالم
I presume that source is simply a string containing the byte values, as this is one thing not quite clear from your question.
You first need to turn that into a byte array. Of course you first need to remove the blanks.
// Initialize the byte array
string sourceNoBlanks = source.Replace(" ", "").Trim();
if ((sourceNoBlanks.Length % 2) > 0)
throw new ArgumentException("The length of the source string must be a multiple of 2!");
byte[] sourceBytes = new byte[source.Length / 2];
// Then, create the bytes
for (int i = 0; i < sourceBytes.Length; i++)
{
string byteString = sourceNoBlanks.Substring(i*2, 2);
sourceBytes[i] = Byte.Parse(byteString, NumberStyles.HexNumber);
}
After that you can easily convert it to string:
string result = Encoding.UTF32.GetString(sourceBytes);
I suggest you read up on the UTF32 encoding to understand little/big endian encoding.
I am trying append byte array to string builder, but not getting the result.
I have to return it to the web service in the form of byte array.
See my code below:
WriteableBitmap wbitmp = new WriteableBitmap((BitmapImage)image1.Source);
wbitmp.SaveJpeg(ms, 400, 400, 0, 100);
bytearray = ms.ToArray();
Now I am appending byte array to string builder.
StringBuilder stb1 = new StringBuilder();
stb1.Append("<image>");
for (int i = 0; i < bytearray.Length; i++)
{
stb1.Append(bytearray[i]);
}
stb1.Append("</image>");
XML String looks like this:
StringBuilder stb1 = new StringBuilder();
stb1.Append("<Title>");
stb1.Append("</Title>");
stb1.Append("<image>");
stb1.Append("</image>");
Thanks in advance!!
Having so little informations it's hard to give some useful response. It looks like you're trying to push some image in HTML/XML-like format. In that case probably you should just convert your binary into Base64 string:
var byteString = System.Convert.ToBase64String(byteArray);
But if your web service requires it to be the raw byte array, then you shouldn't use string builder in the first place.
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));
}
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.
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.