Important Notice: Our web hosting provider recently started charging us for additional visits, which was unexpected. In response, we're seeking donations. Depending on the situation, we may explore different monetization options for our Community and Expert Contributors. It's crucial to provide more returns for their expertise and offer more Expert Validated Answers or AI Validated Answers. Learn more about our hosting issue here.

I’m familiar with programming in C, but how can I use an unsigned byte in Java?

0
Posted

I’m familiar with programming in C, but how can I use an unsigned byte in Java?

0

In C you can have an unsigned 8 bit number ‘unsigned char’. This does not exist in Java, where all numbers (including the byte type) are signed. Some examples in C: unsigned char c1 = 0x00; // 0 unsigned char c2 = 0x7F; // 127 unsigned char c3 = 0x80; // 128 unsigned char c4 = 0xFF; // 255 in Java these numbers have a different value: byte b1 = (byte)0x00; // 0 byte b2 = (byte)0x7F; // 127 byte b3 = (byte)0x80; // -128 byte b4 = (byte)0xFF; // -1 You cannot fully represent an unsigned 8 bit number in the Java byte type, as the values in the range 128..255 do not exist. Note that the short and int types, can deal with the numbers in the 128..255 range: int i1 = 0x00; // 0 int i2 = 0x7F; // 127 int i3 = 0x80; // 128 int i4 = 0xFF; // 255 Also note that with integer arithmetic, numbers are implicitly cast to the ‘int’ type. If you need another type you must cast explicitly: int i5 = b2 + b3; // -1 int i6 = b2 + (b3 & 0xFF); // 255 int i7 = b2 + i3; // 255 byte b5 = (byte)(b2 + i3); // -1

Related Questions

What is your question?

*Sadly, we had to bring back ads too. Hopefully more targeted.

Experts123