1

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);
halfer
  • 19,824
  • 17
  • 99
  • 186
Jacob Reid
  • 33
  • 1
  • 1
  • 6
  • You should not be using a string. Explain what you are doing. Reading a file as a string and then converting to byte[] will get you wrong answer. try this byte[] bytes = Encoding.UTF8.GetBytes(metroTextBox2.Text); – jdweng May 30 '15 at 10:49
  • Possible duplicate of http://stackoverflow.com/questions/16072709/converting-string-to-byte-array-in-c-sharp – user35443 May 30 '15 at 10:57
  • Duplicate of http://stackoverflow.com/questions/10792315/cannot-implicitly-convert-type-string-to-byte – Vikram May 30 '15 at 11:00

3 Answers3

9

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);
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
  • Unfortunately, this hasn't worked for me, probably because i stuffed up on my end :) Sorry, thanks for helping. – Jacob Reid May 30 '15 at 11:00
  • @JacobReid:- You are welcome. I am not sure as to what problem you are facing as this approach works for most of the time! – Rahul Tripathi May 30 '15 at 11:01
  • Im not getting an error at the moment which is great, but its still giving not doing what i want it to do, not your fault, problem on my end thanks :) – Jacob Reid May 30 '15 at 11:02
0
    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
    }
-1

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.

Community
  • 1
  • 1
Ankush
  • 132
  • 1
  • 11