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

Caner
  • 57,267
  • 35
  • 174
  • 180
  • 2
    erm... convert to int then cast to byte? – thecoshman Dec 20 '11 at 14:05
  • 1
    "for some weird reason byte is signed". As opposed to it being unsigned for some weird reason? – DJClayworth Dec 20 '11 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` – Caner Dec 20 '11 at 14:17
  • Yea, not including an unsigned byte type is one of the mysteries that eludes me in Java. – Perception Dec 20 '11 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?"](http://stackoverflow.com/questions/11088/what-is-the-best-way-to-work-around-the-fact-that-all-java-bytes-are-signed) – Jason Braucht Jan 06 '12 at 15:11

4 Answers4

8

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

byte value = (byte)Integer.parseInt("255");
Jesper
  • 202,709
  • 46
  • 318
  • 350
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"));
  }
mpromonet
  • 11,326
  • 43
  • 62
  • 91
1

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

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();
}
Jomoos
  • 12,823
  • 10
  • 55
  • 92