Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / First Aid / July 2006

Tip: Looking for answers? Try searching our database.

Unsigned byte values

Thread view: 
Brian Bagnall - 30 Jul 2006 06:55 GMT
I'm writing some code that passes values from a Java program to a C++
program using an output stream. The C++ program requires a UBYTE, which is
an unsigned byte (values 0 to 255).

Java doesn't have unsigned bytes - only signed bytes (-127 to +127)

So if I want to pass a byte like 128 (0x80) to the C program, how do I do
it?

Java objects to the following code:

byte val = 0x80;

- Brian
Thomas Hawtin - 30 Jul 2006 12:55 GMT
> I'm writing some code that passes values from a Java program to a C++
> program using an output stream. The C++ program requires a UBYTE, which is
> an unsigned byte (values 0 to 255).
>
> Java doesn't have unsigned bytes - only signed bytes (-127 to +127)

-128 to +127.

The sign is only important for performing arithmetic. Whether signed or
unsigned, it's still just eight bits.

> So if I want to pass a byte like 128 (0x80) to the C program, how do I do
> it?

    out.write(128);

OutputStream.write(int) ignores the 24 high-order bits. If you want to
place the value into a byte array first, the equivalent value is -128.
So use -128, (byte)128, 128-0x100, or whatever.

Tom Hawtin
Patricia Shanahan - 30 Jul 2006 15:59 GMT
> I'm writing some code that passes values from a Java program to a C++
> program using an output stream. The C++ program requires a UBYTE, which is
[quoted text clipped - 8 lines]
>
> byte val = 0x80;

0x80 is an int expression. There is an automatic conversion to byte when
an in-range int expression is used as a byte variable initializer. To
use an out-of-range expression, you need a cast:

public class ByteTest {
  public static void main(String[] args) {
    byte val = (byte)0x80;
    System.out.println(Integer.toHexString(val & 0xff));
  }
}

Patricia


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.