2
votes

When I say that 0b11111111 is a byte in java, it says " cannot convert int to byte," which is because, as i understand it, 11111111=256, and bytes in java are signed, and go from -128 to 127. But, if a byte is just 8 bits of data, isn't 11111111 8 bits? I know 11111111 could be an integer, but in my situation it must be represented as a byte because it must be sent to a file in byte form. So how do I send a byte with the bits 11111111 to a file(by the way, this is my question)? When I try printing the binary value of -1, i get 11111111111111111111111111111111, why is that? I don't really understand how signed bytes work.

2
Do you want a raw byte value or a string written to the file? There are solutions for either case.Ted Hopp
I would like raw bytes written the file I believe. Isn't a text file with a bunch of ones and zeros the same as as a file with raw bytes though?user2350459
Not at all. If you write a single byte as raw data to a file, the file size will be 1 byte; if you write a string representation of the bit values, the file size will be 8 bytes. See here or here for discussions of the difference between binary and text files.Ted Hopp
Oh ok, awesome. Thanks for answering all my questions, I really appreciate it.user2350459

2 Answers

10
votes

You need to cast the value to a byte:

byte b = (byte) 0b11111111;

The reason you need the cast is that 0b11111111 is an int literal (with a decimal value of 255) and it's outside the range of valid byte values (-128 to +127).

0
votes

Java allows hex literals, but not binary. You can declare a byte with the binary value of 11111111 using this:

byte myByte = (byte) 0xFF;

You can use hex literals to store binary data in ints and longs as well.

Edit: you actually can have binary literals in Java 7 and up, my bad.