Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to represent 11111111 as a byte in java

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.

like image 262
user2350459 Avatar asked Mar 15 '26 17:03

user2350459


1 Answers

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).

like image 101
Ted Hopp Avatar answered Mar 17 '26 11:03

Ted Hopp