Prasad
Prasad

Reputation: 1188

How to Convert string to byte?

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 );

Upvotes: 1

Views: 282

Answers (3)

Nikolay Kuznetsov
Nikolay Kuznetsov

Reputation: 9579

Try:

int num = Integer.parseInt("00110011", 2);
byte b = (byte)num;

Upvotes: 2

sahmed24
sahmed24

Reputation: 358

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")

Upvotes: -1

NickJ
NickJ

Reputation: 9559

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);

Upvotes: 0

Related Questions