Creating a byte type from a String in Java

12,317

Solution 1

int value = Integer.parseInt(s, 2); // 2 for binary

If you want byte type:

byte value = Byte.parseByte(s, 2); // 2 for binary

Solution 2

Use Byte#parseByte().

Solution 3

Use

byte b = (byte) Integer.parseInt("11111",2);

Solution 4

byte myByte = (byte)Integer.parseInt("11110000", 2);
Share:
12,317

Related videos on Youtube

kakush
Author by

kakush

Updated on June 28, 2022

Comments

  • kakush
    kakush about 2 years

    I have this string 11110000, which represents a byte.

    I want to create a byte from that string, but I can't find any example on-line.

    Can someone please help me?

    • Martin James
      Martin James about 12 years
      What have you tried so far? I found loads of stuff online in seconds. Let me guess - your actual homework question stipulates 'You must not use ParseInt or any other library calls'.
  • Matt Ball
    Matt Ball about 12 years
    BTW, Java bytes are signed, so 11110000 is out of range.
  • dash1e
    dash1e about 12 years
    That's the reason I suggest to use Integer.parseInt.