How to Convert String to Byte Array? - c#

I am getting an error reading:
Cannot implicitly convert type 'String' to 'Byte[]'
I think 'byte[]' is byte array - if it isn't please correct me.
I have tried another solution on this website but I did not understand. I'm making a c# 'RTM tool' and this is what put in :
byte[] bytes = (metroTextBox2.Text);
Array.Resize<byte>(ref bytes, bytes.Length + 1);
PS3.SetMemory(0x2708238, bytes);

You can try like this:
string str= "some string";
var bytes = System.Text.Encoding.UTF8.GetBytes(str);
And to decode:
var decodeString = System.Text.Encoding.UTF8.GetString(bytes);

static void Main(string[] args)
{
string inputStr = Console.ReadLine();
byte[] bytes = Encoding.Unicode.GetBytes(inputStr);
string str = Encoding.Unicode.GetString(bytes);
Console.WriteLine(inputStr == str); // true
}

Try this,
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;
}
n byte to string conversion
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);
}
Credit to this answer.

Related

c# ZLib.Net decompression

I'm trying to decompress a byte array using the ZLib.Net library. Unfortunately my function is always returning two bytes only. The compressed array has 1240 bytes. No one of zlibConst values does return more than two bytes.
Maybe something is wrong with ZLib.Net? (the DLL is taken from here: http://zlibnet.codeplex.com/)
byte[] Decompress(byte [] compressed)
{
byte[] rez = new byte[compressed.Length];
MemoryStream oInStream = new MemoryStream(compressed);
ZInputStream oZInstream = new ZInputStream(oInStream, zlibConst.Z_BEST_COMPRESSION);
MemoryStream oOutStream = new MemoryStream();
byte[] buffer = new byte[2000];
int len;
while ((len = oZInstream.read(buffer, 0, 2000)) > 0)
{
oOutStream.Write(buffer, 0, len);
}
oOutStream.Flush();
byte[] arrUncompressed = oOutStream.ToArray();
oZInstream.Close();
oOutStream.Close();
return arrUncompressed;
}

Converting a byte array to string and back in C#

I am reading a file into a byte array and converting the byte array into a string to pass into a method(I cant pass the byte array itself) and in the function definition I am reconverting the string to byte array. but both the byte arrays( before and after conversion are different)
I am using the following pilot code to test if byte arrays are same.
byte[] bytes = File.ReadAllBytes(#"C:\a.jpg");
string encoded = Convert.ToBase64String(bytes);
byte[] bytes1 = Encoding.ASCII.GetBytes(encoded);
When I use bytes in the api call, it succeds and when I use bytes1 it throws an exception. Please tell me how can I safely convert the byte array to string and back such that both arrays reman same.
Use this:
byte[] bytes = File.ReadAllBytes(#"C:\a.jpg");
string encoded = Convert.ToBase64String(bytes);
byte[] bytes1 = Convert.FromBase64String(encoded);
I'll post a response from another thread:
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);
}
full thread here: How do I get a consistent byte representation of strings in C# without manually specifying an encoding?

How to convert a sub-range of a byte array to a String in C#

In java, you can build a String from a sub-range of a byte[]. How can we perform a similar operation in C#?
Example java code:
byte[] buffer = ...
int offset = ...
int length = ...
String str = new String(buffer, offset, length);
System.Text.Encoding.UTF8.GetString() method has an overload to do this.
byte[] buffer = ...
int offset = ...
int length = ...
String str = System.Text.Encoding.UTF8.GetString(buffer, offset, length);

C# Encoding Conversion

I have an encrypt routine in c++, I translate this to C#:
example:
public void main()
{
string myPwd = "ÖFÖæ6";
string pwdCoded = XEncrypt.EncryptData_Patch_x_Net(myPwd);
//Result OK: ÖFÖæ–6
}
public static string EncryptData_Patch_x_Net(string Data)
{
byte[] bytes = new byte[Data.Length];
for (int n = 0; n < Data.Length; n++)
{
bytes[n] = (byte)Data[n];
}
System.Text.Encoding MyEncoding = System.Text.Encoding.Default;
String MyResult = MyEncoding.GetString(bytes);
return MyResult;
}
I need to make the inverse routine that made it convert from:
ÖFÖæ–6 to ÖFÖæ6 (notice there's a dash in the left string)
I did this last function, but erroneously performs the encoding
public static string DecryptData_Patch_x_Net(string Data)
{
byte[] bytes = new byte[Data.Length];
for (int n = 0; n < Data.Length; n++)
{
bytes[n] = (byte)Data[n];
}
System.Text.Encoding MyEncoding = System.Text.Encoding.GetEncoding(1252);
String MyResult = MyEncoding.GetString(bytes);
return MyResult;
}
This is not encryption and you are seriously complicating what it actually is.
Encoding iso88591 = Encoding.GetEncoding(28591);
Encoding w1252 = Encoding.GetEncoding(1252);
//
string pwd = "ÖFÖæ\u00966"; //The SPA control character will not survice a Stackoverflow post
//So I use \u0096 to represent it
string result = w1252.GetString(iso88591.GetBytes(pwd)); //"ÖFÖæ–6"
string original = iso88591.GetString(w1252.GetBytes(result)); //"ÖFÖæ6" with the hidden control character before 6
Console.WriteLine(result == "ÖFÖæ–6"); //True
Console.WriteLine(original == "ÖFÖæ\u00966"); //True
Your misnamed ...Encrypt... function makes a fundamental error. You take a string, which treat as a char[] (thats fine), then explicitly cast each char to a byte. That is a narrowing conversion. You'll lose any of the high bits and the ability to round trip more unusual chars. If you look at this question it should help to understand.
You could use this function to get the bytes without loss of information,
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;
}
The byte array will round trip on systems that share endianess.
As Esailija states, becuase its simple and it will explicitly return little endian results, you're better off calling
byte[] Encoding.Unicode.GetBytes(string)
To achieve the same.

Error when trying to convert a byte array to string.....c#

This is my code:
byte[] base64String = //this is being set properly
var base64CharArray = new char[base64String.Length];
Convert.ToBase64CharArray(base64String,
0,
base64String.Length,
base64CharArray,
0);
var Base64String = new string(base64CharArray);
When i run this, I get the following error when calling Convert.ToBase64CharArray:
Either offset did not refer to a position in the string, or there is an insufficient length of destination character array. Parameter name: offsetOut
How do i fix this, so i can convert my byte array to a string, or is there a better way to convert a byte array to a string?
Why do you need the char array? Just convert your byte[] directly to a Base64 string:
string base64String = Convert.ToBase64String(myByteArray);
base64 encoding needs 4 characters to encode 3 bytes of input. you have to enlarge your output array.
here is one way you can convert byte array 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);
}
you don't really need to worry about encoding.
more details can be found here
This is a simple form of doing it
string System.Text.Encoding.UTF8.GetString(YourbyteArray)

Categories

Resources