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)

Similar Messages

  • 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 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);         

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

  • Dynamic declaration of XSD datatype in Java

    Hi,
    I am writing a dynamic client for invoking web service solely based on the information from their wsdl documents. Suppose the service uses some customized datatype defined with XSD. Assume I have those datatypes in Java class already. Now I can parse the wsdl document to get the name of a specific datatype of an input part. But how can I declare an object of that datatype in Java with the name of that datatypestored in a variable? One possible solution is to compare it against all possible datatype names, like
    if (name.equals("string") {
    String myObject = new String();
    }else if (name.equals("integer") {
    Integer myInteger = new Integer();
    But obviously this isn't a practical solution since thedatatypes are so many, not even mention user defined ones.
    Can anyone giveme some suggestion? Thanks a lot.
    Yu

    Class.forName(String name)
    The Java Tutorial� - Trail: The Reflection API

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

  • Return CLOB datatype to Java

    Hello,
    Does anyone have any examples of how a CLOB datatype can be returned from a stored procedure and used in java?
    Currently we are building up strings and returning a VARCHAR2 datatype, but are running into the 32k size restriction as some of the strings are too long.
    It seems that converting the strings to CLOBs and then returning is the best solution. Has anyone had a similar problem and solved it?
    Regards,
    Eoin

    Create stored procedure like this :
    create or replace procedure getclob(var out clob) as
    str varchar2(20);
    templob CLOB;
    begin
    str :='mystring';
    DBMS_LOB.CREATETEMPORARY(templob, TRUE, dbms_lob.session);
    dbms_lob.write(templob,length(str),1,str);
    var :=templob;
    DBMS_LOB.FREETEMPORARY(templob);
    end;
    java program to call above stored procedure
    import java.sql.*;
    import oracle.jdbc.driver.*;
    class SPLobInJava
    public static void main(String args[]) throws Exception
    DriverManager.registerDriver(new
    oracle.jdbc.driver.OracleDriver());
    Connection conn = DriverManager.getConnection
    ("jdbc:oracle:thin:@insn104:1521:ora9idb", "scott", "tiger");
    CallableStatement cs;
    cs = conn.prepareCall("{call getclob(?)}");
    cs.registerOutParameter(1,java.sql.Types.CLOB);
    cs.execute();
    Clob clob =cs.getClob(1);
    // do whatever you want with the clob
    System.out.println(clob.getSubString(1,5));
    cs.close();
    conn.close();
    }

  • Error 'Inconsistent datatypes' with Java classes

    Hi,
    I have some Java classes loaded in Oracle 8.1.6, mapped as Object Types, so when I create one object from PL/SQL, JVM ought to create the matching Java object, communicating via the SQLData interface.
    Unfortunately, after the code:
    pippo:=OraMailer('mail.server.com','mymail');
    that creates the PL/SQL object, any code that use member procedures or function wrapping instance methods of the Java class fails with the error 932: Inconsistent datatypes.
    I looked for a mistake in my PL/SQL and Java code, but no error was found.
    It is very important: help me!!!
    Thx

    So here is what you are doing:
    ArrayList results = //get employees from database
    ListIterator langIt = results.listIterator();
    while (langIt.hasNext()) {
      Employee emp = langIt.next();
      String name2 = emp.getName();
      String SSNo = emp.getSSNum();
      results.add(name2);
      results.add(SSNo);
    }So you get a list or Employee objects, then you get an iterator over the list. For each Employee in the list you add the name and SSNo as Strings back to the same list. From the API for ConcurrentModificationException the exception can be thrown when you modify a collection while iterating over the collection - which is precisely what you are doing.
    The ListIterator interface allows you to modify the list through its own methods. Try using:
      langIt.add(name2);
      langIt.add(SSNo);instead.
    Why are you taking the name and SSNo out of the Employee object and placing them back in the same List anyway? That makes no sense to me.

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

  • Why is there no unsigned type is java?

    Just wondering? Why no unsigned int or unsigned long? I have often used these in the past but java requires me to do some clever stuff to get over the limitation.

    i found this on the net somewhere. it doesn't mention anything about java but it does seem to fit the typical "don't include anything that can be confusing or misunderstood" mold that java utilizes:
    "One problem is that unsigned types tend to decrease your
    ability to detect common programming errors. Another is that
    they often increase the likelihood that clients of your classes
    will use the classes incorrectly.
    Consider first error detection. Suppose a programmer defines
    an Array object as follows:
    int f(); // f and g are functions that return
    int g(); // ints; what they do is unimportant
    Array<double> a(f()-g()); // array size is f()-g()
    There�s nothing wrong with this definition for a, except for the
    possibility that the programmer writing it made an error. Instead
    of the size of the array being f()-g(), perhaps it
    should have been g()-f(). Or maybe it should have been
    f()+g(). Or possibly it should have been f()-g()+1; off-byone
    errors are certainly common enough. Heck, it�s even possible
    that f()-g() is correct, but f() or g() is returning a
    bad value. Any of these scenarios could lead to the Array
    constructor being passed a size that was less than zero. As
    the author of the Array class, there�s no way you can keep
    clients from making mistakes such as these, but you can do
    the next best thing: you can detect such errors and act on
    them.
    Well, actually, maybe you can�t. You can�t if you declared Array�s
    constructor to take an unsigned value, because if a
    negative number is passed to a function as an unsigned, the
    number seen by the function isn�t negative at all. Instead, it�s
    a very large positive number. As a result, you�d have no way
    within the Array constructor of distinguishing between a
    large, but valid, positive size value and a large, but invalid,
    positive size value arising from passing in a negative number.
    Hence, you�d be unable to detect programming errors that result
    in negative array sizes being requested. Because such errors
    are not uncommon, this makes your class easy to use
    incorrectly."

  • Select returns negative values for unsigned datatypes in MySQL DB

    Hi, I have a table in a MySQL database where some fields are declared as "unsigned".
    Example:
    CREATE TABLE countries (
    Country_id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    Number SMALLINT UNSIGNED NOT NULL
    My problem is when inside a .xsql file, I try to do a select:
    <xsql:query>
    select Number from countries where Country_id="15"
    </xsql:query>
    If inside the Database, Number always goes from 0 to 65535 (UNSIGNED SMALLINT),
    the resulting XML of that query will always show negative values if Number is
    bigger than 32767 (so it ignores the "UNSIGNED").
    Have you seen something like this before? Do you kwno what I'm doing wrong or what
    can I do to retrieve the values unsigned?
    Thanks a lot!
    David

    hi muneer
    >
    We are facing a strange issue in our R12.1.3 Ebiz instance (DB 11.2.0.1) - Solaris Sparc 64 bit - 2 node (1 node Apps, 1 node DB).
    Some of the purchase orders are having a negative purchase order number.
    SQL> select segment1 from PO_HEADERS_ALL where segment1 < '0';
    SEGMENT1
    -7951814
    -8960847please see
    Error: Purchase Order Creation Could Not Be Initiated, But PO Was Created With Negative PO Number And No Distributions [ID 789464.1]     To Bottom     
    PO Creation Process Failed In Sourcing And Creates Document With Negative Numbers [ID 1479616.1]
    Purchase Order Receipt FAQ (P4312) [ID 1306869.1]
    How it could happen. Any suggestions please !looks like a bug
    Can a Purchase Order (PO) Be Created With Negative Quantity or Price? [ID 241389.1]
    AppsMasti
    Sharing is caring

  • Java newbie help (type casting, 64bit unsigned Long)

    Hi I am java newbie and need help on my project. I have a few questions. Can you put strings in a hashtable and test for their being their with the appropriate hashtable method? I want to test for equal strings, not the same object. Second question can you use all 64 bits of an unsigned long? java doesn't seem to allow this. Any packages that do?
    Thanks,
    Dave

    Try casting it to Long instead of long. Long (capital L) is an Object, while long (lower case l) is not. You may also check to make sure the value isn't null. I would have thought that autoboxing would have worked here unless the value was null. But I am no expert on autoboxing.
    Edit >> Checking for null ain't a bad idea but has nothing to do with the problem - this is a compile time problem. Sorry.
    Also>> This code should work:
    long cTime=(Long)session.getAttribute("creationtime");Edited by: stevejluke on Jul 1, 2008 11:00 AM

  • Java datatype for MySQL DATE?

    Hello!
    I want to read the content of a database table and store it in a linked list.
    My problem is that i dont know what datatype in Java to use for storing the MySQL type DATE.
    Can i use different types for that purpose? Which type is best?
    Thank you

    mattias_westerberg wrote:
    Hello!
    I want to read the content of a database table and store it in a linked list.
    My problem is that i dont know what datatype in Java to use for storing the MySQL type DATE.
    Can i use different types for that purpose? Which type is best?
    Thank you[java.sql.Date|http://java.sun.com/javase/6/docs/api/java/sql/Date.html]
    The best way to store it depends on what you want to do with it. Ultimately you could store it however you wish: bytes, a string, serialized to disk somehow, but a java.sql.Date is what your JDBC API will be taking so it would be convenient to use that if you want to modify the date and store it back to the database.

  • Java Objects for Oracle datatypeJava Objects for Oracle user-defined datatype

    I'm trying to create a Java object that maps to VARRAY of numbers.
    I created a type "NUMARRAY" which is a varray of numbers.
    I also created a type "NUMCOLLECTION" which is an object and contains "NUMARRAY"
    The plan was to create the java object to map to numcollection. My question is can I map a java type directly to the NUMARRAY type, or must it map to an object? (here I'm referring to 'CREATE TYPE NUMARRAY AS VARRAY" or "CREATE TYPE NUMCOLLECTION AS OBJECT" in sql.
    Also, if I do need to write java objects for both types? And if I do, do both need to implement SQLData?
    I'm trying to create a Java object that maps to VARRAY of numbers.
    I created a type "NUMARRAY" which is a varray of numbers.
    I also created a type "NUMCOLLECTION" which is an object and contains "NUMARRAY"
    The plan was to create the java object to map to numcollection. My question is can I map a java type directly to the NUMARRAY type, or must it map to an object? (here I'm referring to 'CREATE TYPE NUMARRAY AS VARRAY" or "CREATE TYPE NUMCOLLECTION AS OBJECT" in sql.
    Also, if I do need to write java objects for both types? And if I do, do both need to implement SQLData?
    Does anyone have an example? Your expertise would be much appreciated.
    Thanks,
    Roxanne
    null

    Hi Roxanne,
    I have the same problem if you get an idea or answer..I have a problem in updating and inserting in Varray datatype from java object of Objects (arraylist)..
    please mail me
    [email protected]
    Bye
    I created a type "NUMARRAY" which is a varray of numbers.
    I also created a type "NUMCOLLECTION" which is an object and contains "NUMARRAY"
    The plan was to create the java object to map to numcollection. My question is can I map a java type directly to the NUMARRAY type, or must it map to an object? (here I'm referring to 'CREATE TYPE NUMARRAY AS VARRAY" or "CREATE TYPE NUMCOLLECTION AS OBJECT" in sql.
    Also, if I do need to write java objects for both types? And if I do, do both need to implement SQLData?
    I'm trying to create a Java object that maps to VARRAY of numbers.
    I created a type "NUMARRAY" which is a varray of numbers.
    I also created a type "NUMCOLLECTION" which is an object and contains "NUMARRAY"
    The plan was to create the java object to map to numcollection. My question is can I map a java type directly to the NUMARRAY type, or must it map to an object? (here I'm referring to 'CREATE TYPE NUMARRAY AS VARRAY" or "CREATE TYPE NUMCOLLECTION AS OBJECT" in sql.
    Also, if I do need to write java objects for both types? And if I do, do both need to implement SQLData?
    Does anyone have an example? Your expertise would be much appreciated.
    Thanks,
    Roxanne
    null

Maybe you are looking for

  • Fusion drive

    Dear sir , I have imac with retina display ..and with i5 8 gb ram and 1 tb hdd . When I was buy that time in india fusion drive is not available. Now I want to upgrade my mac and I want to add add ssd  hard drive in to my mac so my mac work fast .. K

  • Why is there increased overhead(performance) in NAV than DISPLAY attribute?

    Hi, I understand that navigational attibutes lead to increased overhead because of the additional joins: The join between Fact table and dimension table ( I guess on DIM ID) and then the additional join between the Dimension and the Master Data table

  • Speaker on left side scratchy and not clear

    Any fix for the speaker on the left side scratchy for a Pavilion dv5?

  • Security problem en S860

    Hola, tras varios días con mi nuevo S860 y mi recien llegada a Android (desde IOS) comienzo a meter los primeros patones.  Resulta, que el otro día desinstale desdde Link2SD algunas aplicaciones que venian con el telefono que no pensaba usar y otras

  • Converting to DNG - is it safer?

    I know this have probably been covered many times before, so please go easy on me... plus sorry if I'm talking crap!!! I'm always worried about getting a corrupting database again... I've set LR to always back up the database on each launch... but th