4

Is there any way to read bytes in Java and to have the same "format" result than in C#?

Indeed in Java, bytes are signed (-128, +127), where in C# it's not (0, 255).

I'm sending files with a java application to a server who is expecting only positive bytes, so it's not working as soon as I have some negative bytes.

Concrete problem : when I'm serializing my bytes[] into json (using gson), I have values from -128 to + 127 whereas I'd like to have value from 0 to 255.

Hope it's clear enough.

Thank you.

3
  • 4
    There is no such thing as a 'positive byte'. A byte is 8 bits. The difference is how you represent numbers with bytes. C# bytes are unsigned using plain ol' base 2 and java bytes are between -128 to 127 using 2's complement. 11111111 and 11111111 are the same byte both in C# and java. Commented Feb 6, 2013 at 23:54
  • Please tell more about the concrete problem for which you incorrectly thought that this is the solution. Commented Feb 6, 2013 at 23:55
  • @BalusC : I edited my problem it was not clear indeed. Commented Feb 6, 2013 at 23:59

2 Answers 2

12

If you want to get [0-255] values in the Java app, use a construct like (b & 0xff) to get a positive int from a byte.

Sign up to request clarification or add additional context in comments.

Comments

-2

Java byte is signed from -128 to 127, if u want to get the representation from 0 to 255 i use this 2 functions

public static byte fromIntToByte(String value) throws Exception {
        return fromIntToByte(Integer.parseInt(value));
    }

    public static byte fromIntToByte(int value) throws Exception {
        String stringByte = "";
        if (value < 0 && value > 255) {
            throw new Exception("Must be from 0<=value<=255");
        }
        if (value <= 127) {
            for (int i = 0; i < 8; i++) {
                stringByte = String.valueOf(value % 2) + stringByte;
                value = value / 2;
            }
        } else {
            value = value / 2;
            for (int i = 0; i < 7; i++) {
                stringByte = String.valueOf(value % 2) + stringByte;
                value = value / 2;
            }
            stringByte = "-" + stringByte;
        }
        System.out.println(stringByte);
        byte b = Byte.parseByte(stringByte, 2);
        return b;
    }

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.