简体   繁体   中英

Java byte Insert value error string to byte

I have class that have one member myByte as follows.

public class ByteClass {
    private Byte myByte;
    public Byte getMyByte() {
        return myByte;
    }
    public void setMyByte(Byte myByte) {
        this.myByte = myByte;
    }
}

I have string value which is FF and I need to assign it to the class member, how should I do that since when I try it ass follows I got error in the compile time

Type mismatch: cannot convert from byte[] to byte I understand that I cant use Array of byte for the string but I have tried to do that in several of ways without any success .any Idea how can I set the value FF to the class ?

public class ByteHanlder {

    public static void main(String[] args) {
        String str = "FF";
        byte temp = str.getBytes();
        Byte write_data = new Byte(temp);
        ByteClass byteClass = new ByteClass();
        byteClass.setMyByte(temp);
        System.out.println(byteClass.getMyByte());
    }
}

Assuming you really do just want to store a byte, you can use:

int value = Integer.parseInt("FF", 16); 
x.setMyByte((byte) value);

Now that will give you a value of -1 if you look at it in the debugger - but that's just because bytes are signed, as other answerers have noted. If you want to see the unsigned value at any time, you can just use:

// Only keep the bottom 8 bits within a 32-bit integer, which ends up
// treating the original byte as an unsigned value.
int value = x.getMyByte() & 0xff;

You can still just store a byte - and then interpret it in an unsigned way rather than a signed way. If you really just want to store a single byte - 8 bits - I suggest you don't change to using a short .

Having said all this, it's somewhat odd to need a mutable wrapper type just for a byte... perhaps you could give us more context as to why you want this, and we may be able to suggest cleaner alternatives.

Your String "FF" seems to be a hex value, right? So you actually want to convert it to the byte value of 255.

You can use a method like described here to convert a hex string to a byte array: Convert a string representation of a hex dump to a byte array using Java? .

In your case, you could adapt that method to expect a 2-letter string and return a single byte instead of a byte array.

String.getBytes return a bytearray so you can not assign a bytearray to a byte.

If you want to set FF hex value then you could use

setMyByte((byte)0xff);

But there is still a problem 0xff is of 2 byte size but byte type is of 1 byte. In that case you can use short instead of byte

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM