'JAVA: Weird byte values of byte array when serializing objects

currently i'am working on my own crc32 implementation. I'am almost done! Now i want to test it and i want to serialize some object. Here's my code:

     String test = "Hallo 123 Test";
        
        try {
            sysoutBytes(serialize(test));
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

     public static byte[] serialize(Object obj) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ObjectOutputStream os = new ObjectOutputStream(out);
        os.writeObject(obj);
        return out.toByteArray();
    }

But now i have the problem, that the bytes are very weird. Here's my output:

-84 -19 0 5 116 0 14 72 97 108 108 111 32 49 50 51 32 84 101 115 116

I just need the binary version of this because my crc code only works with 0 and 1 bytes.

Thanks for helping!



Solution 1:[1]

These are not weird byte values. These are normal byte values, which range in 0..255, though the way you are printing them, they show up as -128..127. Those negative values are normally printed as positive, by adding 256.

0 and 1 are bits, not bytes. Each byte consists of eight bits. You can pick apart each of those bytes to get the eight bits. You need to decide if you want the most significant or least significant bits first. Let's say the latter. You can get the low bit with x & 1 (x is the byte). Then do x >>= 1 to shift x down one bit. Then the next to lowest bit is x & 1. And so on.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mark Adler