2

How can I convert a string to byte? For example, Byte.parseByte("255"); causes NumberFormatException since (for some weird reason) byte is signed in java so the maximum value it can have is 127.

So I need a function such that

public static byte toByte(String input) {
...
}

And for example toByte("255"); should return -1(ie bits: 11111111)

Something like implementation of 2s complement

5
  • 2
    erm... convert to int then cast to byte? Commented Dec 20, 2011 at 14:05
  • 1
    "for some weird reason byte is signed". As opposed to it being unsigned for some weird reason? Commented Dec 20, 2011 at 14:09
  • Its unsiged in c,c++,delphi,c#,... I think it doesnt make sense because byte is used mainly for binary data so should have no sign. If there is a need for memory-space-efficient number then there is short Commented Dec 20, 2011 at 14:17
  • Yea, not including an unsigned byte type is one of the mysteries that eludes me in Java. Commented Dec 20, 2011 at 14:22
  • A very similar question has been asked before and several good answers were provided. See: "What is the best way to work around the fact that ALL Java bytes are signed?" Commented Jan 6, 2012 at 15:11

4 Answers 4

8

Use Integer.parseInt("255") and cast the resulting int to a byte:

byte value = (byte)Integer.parseInt("255");
Sign up to request clarification or add additional context in comments.

1 Comment

Dam my timid nature! that should be my answer!
1

byte value = (byte)Integer.parseInt("255");

Comments

1
   public static void main(String[] args) {    
     String s = "65";
     byte b = Byte.valueOf(s);
     System.out.println(b);

     // Causes a NumberFormatException since the value is out of range
     System.out.println(Byte.valueOf("129"));
  }

Comments

0

I am thinking of the following implementation!

public static byte toByte(String input) {
    Integer value = new Integer(input);

    // Can be removed if no range checking needed.
    // Modify if different range need to be checked.
    if (value > 255 || value < 0)
        throw new NumberFormatException("Invalid number");

    return value.byteValue();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.