1

How can I convert a String containing number like "00110011" to bytes using Java? I have tried some code as follows-

System.Text.Encoding enc = System.Text.Encoding.ASCII; 
byte[] myByteArray = enc.GetBytes("a text string"); 
string myString = enc.GetString(myByteArray );
Prasad
  • 1,188
  • 3
  • 11
  • 29

3 Answers3

2

Try:

int num = Integer.parseInt("00110011", 2);
byte b = (byte)num;
Nikolay Kuznetsov
  • 9,467
  • 12
  • 55
  • 101
0

Do you mean convert a binary number expressed as a string to an int?

If so, then:

String binaryString = "00110011";
int base = 2;
int decimal = Integer.parseInt(binaryString, base);
NickJ
  • 9,380
  • 9
  • 51
  • 74
  • If binaryString is having string "11000000" it shows NumberFormatException : Value Out of range. – Prasad Mar 19 '13 at 13:33
-1

Try something like this

String str =  "00110011";
byte[] bytes = str.getBytes();

Alternatively you can send an Encoding to getBytes like "UTF-16", so str.getBytes("UTF-16")

Harry Joy
  • 58,650
  • 30
  • 162
  • 207
sahmed24
  • 358
  • 2
  • 3
  • 13