Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StringBuilder and byte conversion

Tags:

I have the following code:

StringBuilder data = new StringBuilder(); for (int i = 0; i < bytes1; i++) {      data.Append("a");  } byte[] buffer = Encoding.ASCII.GetBytes(data); 

But I get this error:

cannot convert from 'System.Text.StringBuilder' to 'char[]' The best overloaded method match for 'System.Text.Encoding.GetBytes(char[])' has some invalid arguments 
like image 283
R.Vector Avatar asked Feb 02 '12 03:02

R.Vector


People also ask

How to convert StringBuilder to bytes?

StringBuilder data = new StringBuilder(); for (int i = 0; i < bytes1; i++) { data. Append("a"); } byte[] buffer = Encoding. ASCII. GetBytes(data.

Can we convert byte to String in Java?

Given a Byte value in Java, the task is to convert this byte value to string type. One method is to create a string variable and then append the byte value to the string variable with the help of + operator. This will directly convert the byte value to a string and add it in the string variable.


1 Answers

The following code will fix your issue.

StringBuilder data = new StringBuilder(); for (int i = 0; i < bytes1; i++) { data.Append("a"); } byte[] buffer = Encoding.ASCII.GetBytes(data.ToString()); 

The problem is that you are passing a StringBuilder to the GetBytes function when you need to passing the string result from the StringBuilder.

like image 168
Scott Smith Avatar answered Sep 28 '22 07:09

Scott Smith