Unsigned byte in Java

Hi,
How can I declare a byte variable as unsigned, like we can do in C?
In other words, I want 11111111 to represent 255 and not 127 (as in 2's comp.)
Thanks,
Maya.

Hi,
How can I declare a byte variable as unsigned, like we
can do in C?
In other words, I want 11111111 to represent 255 and
not 127 (as in 2's comp.)
Thanks,
Maya. Quote from the help desk:
"In Java, integers are always signed, whereas in C/C++ they are signed by default."
I assume this means bytes are also always signed.

Similar Messages

  • How to express the unsigned byte in Java?

    we know that data are normally in unsigned byte format when communicating with COMM. How to express the unsigned byte in Java? java only supports 127 ~ -127 as byte, but I need 255~0.
    Anyone know how?
    Thanks!

    You mean when a byte ( -127) converts to a int, it
    will become 255?In your example -1 will be printed in both cases because of the implicit conversion Java makes. The 0xff in the byte will become 0xffffffff in the int. Both are interpreted as -1.
    This will keep the byte bitpattern intact and print -1 and 255.
    byte b = (byte)(0xff);
    int i = (b & 0xff); // mask of rightmost 8 bits
    System.out.println(i);         

  • Unsigned bytes?

    I'm reading binary data as unsigned bytes but Java is insisting on using signed bytes (so when I try to use Byte.parseByte("88"), I get a NumberFormatException). I can't find anything in the API that looks like it'll do this for me. Help please!

    Bytes are always unsigned in Java.
    It's not clear what you're trying to do. First you say "binary data," then you say "parseByte," which would be used on textual data.
    If it's just bytes, then reading the bytes will give you the proper values. If you want to see those values as unsigned integers, so that 0xFF is 255, rather than -1, then you can do int ii = bb & 0xFF; Can you clarify what you're trying to do?

  • Unsigned byte: Java byte data type (0-255)?

    I need an "unsigned" byte type.
    How can I implement a one byte data type with values from 0-255 in Java?

    No there isn't an unigned byte, but you don't need
    one. You just separate storage representation from
    calculation representation. When you store the
    "unsigned byte" you use a signed byte. When you make
    calculations on the "unsigned byte" you use an
    integer. For this you need two conversion functions,
    public static int toInt(byte b) {
    return b + 128;
    public static byte toByte(int i) {
    return (byte)(i - 128);
    }These amazing functions must be tested off course.
    public void testUnsigned(int unsgn) {
    byte bA[] = new byte[1];
    int i = unsgn;          // 0 to 255
    bA[0] = toByte(i);    // stored as -128 to 127
    int j = toInt(bA[0]); // 0 to 255
    if (i==j)
    System.out.println("Yes it works!");
    Sorry, but your code doesn't work. I also tried the byte & 0xFF and I get strange results too. 0xFF transfer to 129, which (I think, but maybe I'm wrong) should transfer to 255 (0xFF == 1111 1111, no?). After some tests, I found that "ounos" solution is the best fitted (byte < 0 ? b+256 : b)
    If you only do a (byte + 128), you'll get, for example:
    0000 0000 (should be 0) == 128
    I think that only 1 case is enough to proove that this code doesn't work... :-)

  • Writing binary files & trouble with no unsigned byte type

    I've got a fair amount of Java experience, enough to know what I'm doing most of the time but I do have a vast experience with C & C++ which helps my Java. I've stumbled across a problem when trying to write out files in binary.
    If I was to write out a binary file, I would always choose C/C++ to do this because simply because I'm at ease with the implementation.
    I've now written a Java program which needs to output a file in binary and I'm having real issues doing the most simple things because of no unsigned support.
    I want to write out elements byte-by-byte and make use of the 8-bits provided in the byte type in Java.
    Let's assume I've done my processing and I end up with an int. I know that this int is 0-255 in value. I now want to pack it into a byte and write it to my file. How do I go about assigning the byte without Java 'converting' it to a signed byte? I simply want to copy the lower 8-bits of the int and duplicate them into the byte variable - no conversion.
    In C you would do something like this:
    char mySignedChar = *( (char*)&(unsigned char)myInt ) );
    What's the Java equivalent? Am I going about this the right way?

    Whether a byte is signed or unsigned only matters if one is doing arithmetic on it. If the int is 0-255 then you just cast to a byte using
    byte theByte = (byte)theIntValue;When reading back you just use
    int theByteAsAnInt = theByte & 0xff;

  • Converting bytes to unsigned bytes

          int u=0;
          int i=32;
    byte []  data1 = new byte[1024];
    int[] unsignedValue=new int[1024];
    while(u<100){
                        unsignedValue[u] =data1[i] & 0xff;
                          u++;
                          i++;
                       } from input stream iam storing bytes in data1.now i want to convert specific bytes to unsigned bytes.
    here i tryed in the above way but i want to convert
    2 to 8
    12 to 18
    22 to 28
    bytes to unsigned and i want to store how can i do this?

    nanda_java wrote:
    in my fist post only i multiplyes with 0xff .and i gave code ...my question is how to multiply only specific
    2 to 8
    12 to 18
    22 to 28
    bytes with 0xff .the bytes are in data1.I have no idea what you're saying, and I have no idea what the significance of those ranges is.
    Look, you've already been told this twice: Say you get the byte 0xFE. That byte is neither signed nor unsigned. Get that into your head. It's simply a byte. The concept of signed/unsigned only comes into play when you decide to treat that as an integer value. You might want it to represent -2, or you might want it to represent 254. If you store it in a Java byte, it will represent -2. You cannot change that. If you want 0xFE to mean 254, then mask it with 0xFF and store it in an int.
    byte b = -2;
    System.out.println(b & 0xFF); // prints 254Furthermore, as already stated, in many cases it doesn't matter if it's signed or unsigned. If you do addtion, subtraction, multiplication (I think), AND, OR, XOR, you'll get the same byte result, regardless of whether you consider it signed or unsigned, and again, signed/unsigned only matters if you care about the numerical value of that signed result, rather than simply its bit pattern. 0xFE - 0x01 = 0xFD, and you can take that as -2 -1 = -3 or as 254 - 1 = 253. The bytes are the same regardless.
    What part are you not understanding? Don't just keep repeating the same thing about how it's unsigned and 2 to 8 and all that nonsense.
    So please, define your problem more clearly.
    Edited by: jverd on Jan 10, 2008 8:53 AM

  • Unsigned Long in java

    Hi all,
    I have a code in C which i want to convert into java.. Iam facing problem because java does not support
    unsigned long.The code in c look like this:
    WCD.cardno = ( SerBuf[3]* 0x00010000UL+
    SerBuf[4]* 0x00000100UL+
    SerBuf[5]* 0x00000001UL);
    I want to convert this code into java. What i have done is something like this
    cardno = (tempBuffer[3]*0x01000000 + tempBuffer[4]*0x00010000 + tempBuffer[5]*0x00000100 +tempBuffer[6]*0x00000001);
    Can anyone help me out. This program is for serial port implementation.
    Thanks
    Kiran

    kiranJNI wrote:
    Basically how can we achieve unsigned long in java???In your case, this isn't going to be a problem for two reasons.
    AFAIK, there aren't any numbers where multiplying them as unsigned numbers is going to be different from multiplying them as signed numbers and still give a valid result. To make this easier, let's work with signed vs unsigned bytes. Negative numbers are those in the range 0x80 to 0xFF; these are the only numbers where the "value" of the byte differs between signed and unsigned. Now think of those numbers as unsigned numbers. The only unsigned numbers you could multiply them by and still remain within the range of a byte are 0 and 1. If you multiply by 2, the result is 0x100, which is larger than what a byte can represent. If the result will remain within the range of the data type, it don't think there are any numbers where signed and unsigned multiplication return a different bit pattern.
    Furthermore, your example doesn't even need multiplication. You're multiplying by powers of 2, so all you really need is a series of shifts and adds.

  • How to map C/C++ unsigned char[] to Java

    hi all,
    I'm using w2k OS.
    Given that C code:
    BYTE *fBuf;
    fBuf = new BYTE[256];
    Is there anyone of you know how to pass/map the unsigned char to java?
    regards
    elvis

    why did you classify this as byte? how do you did
    that?They probably guessed. It is probably a good guess.
    You can use the following to determine the size exactly.
    First determine what "BYTE" is exactly. You will have to find that in an include file somewhere. Your IDE might do this for you automatically.
    So, for example you might find the following...
    typedef unsigned char BYTE;
    So then you would know that the type is actually "unsigned char".
    Once you have this information you then look in limits.h (this is an ANSI C/C++ file so it will exist somewhere.) In it you find the "..._BIT" that corresponds to the type. For the type given above you would be looking for "CHAR_BIT" (because unsigned and signed chars are the same size.)
    On my system that would be...
    #define CHAR_BIT 8
    That tells you that there are 8 bits in the BYTE value. So now you need to find a java type that also has at least 8 bits. And the java "byte" value does.

  • I'd like to use UNSIGNED byte .. is it possible?

    Are there any UNSIGNED BYTE variable in JAVA?
    Everyone says use SHORT instead , but it is not
    the best solution... I really Need bytes...
    Thanks...

    Yes; everything you need*) to do with unsigned bytes you can do with signed bytes.
    *) you don't really need to do a unsigned byte division, do you...

  • Unsigned problem with java

    I need to implement a comparation method like this:
    int compare(byte[] a,byte[] b)
      len=a.length; 
      if(len!=b.length)
        throw new RuntimeException("");
      for(int i=0;i<len;i++)
        if(a>b[i])
    return 1;
    else if(a[i]<b[i])
    return -1
    return 0;
    the problem is,the argument byte array is provided as Unsigned,i.e.it may contain value larger than 127(of course less than 256,it is read from a stream),and java doesn't support unsigned byte, then the above method would go wrong.
    Of course I could do bit check in the method. But this method is mission critical. A typical client request may cause to excute this method tens of millions times. Do more operation in this method would not be time affordable.
    The method is indeed to check the first different bit,and the one contain 1 on that bit considered larger.
    who could find an efficient way to implement the method?

    public class SpeedTester
        public static final long OUTER_ITERATIONS = 10000;
        public static final long INNER_ITERATIONS = 1000;
        public static void main(String[] args)
            Data[] data = {new ByteTestData()};
            Test[] tests = {new ByteCompareA(), new ByteCompareB(), new ByteCompareC()};
            long[] times = new long[tests.length];
            for (int j = 0; j < OUTER_ITERATIONS; j++)
                for (int k = 0; k < data.length; k++)
                    data[k].create();
                for (int k = 0; k < tests.length; k++)
                    times[k] += test(tests[k]);
            for (int j = 0; j < tests.length; j++)
                System.out.println(tests[j].getClass().getName() + ": " + times[j] + " - "
                    + ((double) times[j]) / (OUTER_ITERATIONS * INNER_ITERATIONS)
                    + " millis per test");
        public static long test(Test test)
            long start = System.currentTimeMillis();
            for (int j = 0; j < INNER_ITERATIONS; j++) test.test();
            return System.currentTimeMillis() - start;
    interface Data
        public void create();
    interface Test
        public void test();
    class ByteTestData implements Data
        public static int PERCENT_MATCHING = 99;
        public static final int LENGTH  = 10;
        private Random random = new Random();
        public static final byte[] BYTES_A = new byte[LENGTH];
        public static final byte[] BYTES_B = new byte[LENGTH];
        public void create()
            for(int i=0; i < LENGTH; i++) {
                BYTES_A[i] = (byte) (0x00FF & random.nextInt());
                if (random.nextInt(101) < PERCENT_MATCHING) {
                    BYTES_B[i] = BYTES_A;
    } else {
    BYTES_B[i] = (byte) (0x00FF & random.nextInt());
    class ByteCompareA implements Test
    public void test()
    compare(ByteTestData.BYTES_A, ByteTestData.BYTES_B);
    static final int compare(byte[] a,byte[] b)
    if(a[0]!=b[0]) return (a[0]&0xff)-(b[0]&0xff);
    int len=a.length;
    for(int i=1; i<len; i++) {
    if(a[i]!=b[i]) return (a[i]&0xff)-(b[i]&0xff);
    return 0;
    class ByteCompareB implements Test
    public void test()
    compare(ByteTestData.BYTES_A, ByteTestData.BYTES_B);
    static final int compare(byte[] a,byte[] b)
    int len=a.length;
    int i1,i2;
    for(int i=0;i<len;i++) {
    i1=a[i]&0xff;
    i2=b[i]&0xff;
    if(i1>i2) return 1;
    else if(i1<i2) return -1;
    return 0;
    class ByteCompareC implements Test
    public void test()
    compare(ByteTestData.BYTES_A, ByteTestData.BYTES_B);
    static final int compare(byte[] a,byte[] b)
    for(int i=0; i < a.length; i++) {
    if (a[i] != b[i]) {
    if ((a[i] & 0x80) != (b[i] & 0x80)) {
    return a[i] < b[i] ? 1 : -1;
    } else {
    return a[i] > b[i] ? 1 : -1;
    return 0;
    Here's a testing framework for you. You can tweak the ByteTestData class to get something like your expected data. I created another algorithm but it doesn't seem to be an improvement. BTW, my computer seems to be executing in the range of your project specs and it's by no means a beast.

  • Unsigned types in java

    hi there,
    i was wondering if there is any way to handle unsigned int in java. im making some byte processing and i have a "switch case" statement like below
    so when it comes at 0x80 it does not enter the case because it converts it as -1.
    im using java 1.7
    ByteBuffer record;
    pkgId = record.get();
    switch ((int) pkgId) {
    case 0x75:
    break; /* 117 */
    case 0x7D:
    break; /* 125 */
    case 0x80:
    break; /* 128 */
    case 0x82:
    break; /* 130 */
    case 0x86:
    break; /* 134 */
    case 0x87:
    break; /* 135 */
    }

    user8999602 wrote:
    hi there,
    i was wondering if there is any way to handle unsigned int in java.Use a long.
    im making some byte processing and i have a "switch case" statement like below
    so when it comes at 0x80 it does not enter the case because it converts it as -1.
    im using java 1.7
    ByteBuffer record;
    pkgId = record.get();
    switch ((int) pkgId) {
    case 0x75:
    break; /* 117 */
    case 0x7D:
    break; /* 125 */
    case 0x80:
    break; /* 128 */
    case 0x82:
    break; /* 130 */
    case 0x86:
    break; /* 134 */
    case 0x87:
    break; /* 135 */
    }Looks more like you want an unsigned byte. The usual approach to that is to use an int, but you need to mask it. The byte 0x80 has the value -128, so when you simply cast to an int, it sign extends it, and you get 0xFFFFFF80, which is an int value of -128.
    int pkgIdInt = pkgId & 0xFF;
    switch (pkgIdInt);Alternatively, you could just cast each case value to byte, but that's too cluttered for my taste.

  • Convert unsigned bytes (U8) to time date stamp.

    From a CAN device I have the date and time as a series of seven unsigned bytes (U8) as follows:
    Century         example        20
    Year              example       10
    Month           example         4
    Day              example        26
    Hour             example       20   (8:00 PM)
    Min               example       20
    Sec               example         1
    which would be:
                4/26/2010
                20:20:1
    What is the best approach to convertng these seven values to a date/time format for display purposes only?
    Thank you.
    Solved!
    Go to Solution.

    Chuck,
    Here's a couple of ways to do it, but sure there are others.
    The first for numeric inputs or concatenate to a string with second.
    Hope one of these does what you need.
    *Edit - added combining or Century & Year
    Message Edited by jrjones on 04-25-2010 10:40 PM

  • Which kind of array to choose for combining several unsigned byte

    Hi, I have several unsigned byte variables, and want to build them together as an array for future use in configuration saving. Could any one tell me which kind of array I should use? Or should I use "build array"?
    Solved!
    Go to Solution.

    I think you would be better off saving these items individually. It is a bit more work on the code side but it is much easier for a human to edit the file. Use a traditional ini file format such as:
    [Application]
    Station 1 = Enabled
    Station 2 = Disabled
    Logging = Enabled
    Stop on Error = Yes
    This is much more readable for a person. I recommend this sice you are saying this is a configuration file. Generally these will be open for editing by a person.
    If you go with some criptic array format such as
    Parameter = Enable, Enable, Disable, Enable
    You can write a subVI that will return cluster containing your configuration settings. You would also write a similiar subVI for saving the parameters. This VI would also accept the cluster as an input.
    the user will have no clue what they are setting or modifying.
    Here are some examples of VIs I use to handle configuration files.
    Mark Yedinak
    "Does anyone know where the love of God goes when the waves turn the minutes to hours?"
    Wreck of the Edmund Fitzgerald - Gordon Lightfoot
    Attachments:
    Generic Get Section from Config File.vi ‏20 KB
    Get Application Specific Parameters From Config File.vi ‏32 KB
    Get IP Addresses from Config File.vi ‏22 KB

  • Unsigned datatypes in java?

    need help with the following topic:
    I am sending a u_char value (0-255) from an ANSI C server to a JAVA Applet(client). I want to use this value as a counter from 0 to 255.
    The receive buffer in the Applet is of type "byte". If a value larger than 127 arrives, overflow occurs. How do I get the java code to work with values larger than 127, as I want to use that most significant bit as a value and not as a sign representer? It seems as if java does not support unsigned data types...

    first of all, 255 as a value doesn't exist in java for bytes.
    So no, it won't turn 255 into anything.
    It will turn -1 into 255, -2 into 254, -3 into 253, ...., -128 into 128 which is exactly what the OP wants.
    If by 255 you mean the byte value of -1, then here is what will happen
    1. Java converts the byte to an int. Since -1 is negative then the extra space is filled with set bits (1's).
    11111111 -> 11111111111111111111111111111111
    2. The '0xFF &' operation will clear all of the bits except for the lower eight
    11111111111111111111111111111111 -> 00000000000000000000000011111111
    3. and viola, you have a value from 0 to 255 (inclusive)

  • Security in each byte of Java card's EEPROM

    as i undrestand until now in my applet I define a variable and store data in that variable,
    Is it a way to know where these data are stored, I mean I wanna define the memory address of that data by myself,
    caz my card application is multi-app, and maybe in future I want to let someone else load his/her applet in that card beside my applets to do other application
    but from know I wanna think of security that in future let that person to have the memory address from i.e 0x01 up to 0x05
    and have no right to read or write in other memory bytes
    and also each part of memory address should have a security code for authentication...
    what's your idea about this post and what do u sudggest?
    Regards
    Hana

    I'm sorry for my ignorance, but i think that you do not want to mess around with the Card Issuer Keys unless you are the Card Issuer which does not seems like the case.
    I think that you want to use the Secure Channel Protocol inside your own applet(which is what i want to do also) and use your own issued keys.
    Why? Because in a real situation you will not want that your Java Card stuck with only one App, you want it to have as many as the user wants to. For that to happen, the card issuer keeps a keyset to load&install applets, but, when the applet is installed you want to maintain your privacy from the card issuer(and everyone else), so you will need an extra keyset for your own Secure Channel Protocol.
    What i'm saying is that:
    When you enter the Cards Security Domain, you need the cards security domain keys.
    When you select your applet, all your comunications become "plain-text" and you will not have any transaction security.
    I would like to know how to open this SCP channel from my app, but unfortunatelly i cannot help you any further.
    Edited by: rochajoel on Aug 31, 2009 9:48 AM

Maybe you are looking for

  • Is there a way to set an image as a background after i've already gotten my text boxes perfected?

    Sorry, I know the title question is a little confusing so I'll try to better explain. I am brand new to adobe programs, so there may or may not be a very simple solution/way to do this that I don't know about because to be honest I don't know much. I

  • Operations on text strings

    Hi experts,       I have a situation wherein i have to compare the text strings and if it matches i want to copy the below lines to an internal table until it faces some other keyword. Let me explain in detail, I have an internal table like this, sum

  • HT5275 How do I find the password pane in safari? It is mentioned as a new feature, but I can't find it.

    How can I find the password pane in safari? I have looked through all of the obvious menus. Would like to find one of my stored website passwords. Thank you.

  • Offline Processing Credit Card

    Since the secure PDF, which is used to supply the secure CC info to the vendor, no longer includes the CCV that payment forms collect, the Payment Gateway selection of Offline Processing (Process Manually Via Existing Facility) no longer makes any se

  • Error message with forms 6i and OAS

    Hello, I 'm executing an applet (forms6i&OAS), while executing http://mycomputer:8001/web_html/mybase i have the error: keyconfailbundle oracle.forms.engine runformbundle exception java.lang.illegal argument exception: unknown format type... can u pl