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

Similar Messages

  • JAVA primitive data types - Signed/ unsigned etc.

    1. Are the following data types signed or unsigned in JAVA?
    byte, short, int, long, float, double
    2. I have tried using "Integer" in place of "int" and the program runs perfectly. Why is this so when "Integer" is not a reserved word in JAVA?
    Thanks.

    And to answer your first question, byte, short, int, long, float and double are all signed.
    As a part of the core of the language, Sun developed a series of 'collections' classes; Vector, ArrayList, etc. All of these classes, in the days before generics, were able to store instances of the Object class or anything that derived from it. Therefore, to store an int, a float or a double value into one of these collections classes, it was necessary to wrap it up in an instance of one of those classes that derived from Number. These are the wrapper classes that the previous poster alluded to. Typically, the wrapper class has a similar name to the primitive data type but with a capital latter; int - Integer, double - Double, etc.

  • What's wrong with java.util.Date type?

    Hi!
    When I try to persist object having field of type java.util.Date I get the
    following SQL logged by Kodo with subsequent transaction rollback:
    2002-11-14 15:03:35,099 INFO
    [com.solarmetric.kodo.impl.jdbc.ee.ManagedConnecti
    onFactoryImpl.supportcrm/kodo] INSERT INTO BILLY.TT_COMMENTS(COMMENT_TYPE,
    TEXT,
    CREATED_BY, ID, SUBJECT, CREATE_DATE, TT_MAIN_ID) VALUES (1, '1', 10, 279,
    '1',
    {ts '2002-11-14 15:03:35.059'}, 147)
    When I change "{ts '2002-11-14 15:03:35.059'}" with "TO_DATE('2002-11-14
    15:03', 'YYYY-DD-MM HH24:MI')" in SQL editor
    and execute it everything works fine.
    What does "{ts '..'}" mean? Is it a SQL generation error?
    Thank you in advance.
    Best regards,
    Alexey Maslov

    I've created my own dictionary with dateToSQL() method overridden.
    Now it works fine. But it's a kind of strange. Oracle is used often and my
    JDBC drivers
    are the most recent (at least, from the oracle.com).
    Anyway, thank you again.
    "Alexey Maslov" <[email protected]> wrote in message
    news:[email protected]...
    Patric,
    Thank you for response.
    We're using Oracle 8.1.7 via OCI driver from Oracle 9.2.
    I've already tried 2.4.0 and it works fine there but I've found another
    problem there
    preventing me from using it. See my post in solarmetric.kodo.betanewsgroup.
    >
    "Patrick Linskey" <[email protected]> wrote in message
    news:[email protected]...
    That's odd -- what version of Oracle are you using?
    Moving to Kodo JDO 2.4.0
    (http://www.solarmetric.com/Software/beta/2.4.0) will almost certainly
    get rid of this problem, as we use exclusively prepared statements in
    it, and therefore pass dates etc. to JDBC as parameters.
    But, to get things working with your Oracle database and Kodo JDO 2.3,
    you could create your own extension of OracleDictionary and override the
    dateToSQL() method to generate the appropriate TO_DATE() syntax. See our
    documentation for more details on creating custom database dictionaries.
    -Patrick
    Alexey Maslov wrote:
    I've added TRACE level logging for transactions in JBoss and got
    original
    exception:
    NestedThrowables:
    com.solarmetric.kodo.impl.jdbc.sql.SQLExceptionWrapper: [SQL=INSERT
    INTO
    BILLY.T
    T_MAIN(TT_SOLUTION_ID, DELAY_REASON, TT_STATE_ID, ID, CONTACT_PHONE,
    CANCEL_REAS
    ON, OPER_DESCR, TT_TYPE_ID, CREATED_BY, EXP_CLOSE_DATE,SERV_OPEN_DATE,
    OPEN_DAT
    E, FLAGS, TAKEN_BY, TT_CAT_ID, SUBJECT_ID, SUBJECT, SERV_CLOSE_DATE)
    VALUES
    (NUL
    L, NULL, 1, 439, NULL, NULL, '____________ ________________ ________________', 7, 5, {ts
    '2002-11-14 1
    8:38:16.075'}, NULL, {ts '2002-11-14 18:18:16.075'}, 0, NULL, 11,24099,
    '1', NU
    LL)] ORA-00904: invalid column name
    at
    com.solarmetric.kodo.impl.jdbc.runtime.SQLExceptions.throwFatal(SQLEx
    ceptions.java:17)
    at
    com.solarmetric.kodo.impl.jdbc.runtime.JDBCStoreManager.insert(JDBCSt
    oreManager.java:421)
    at
    com.solarmetric.kodo.runtime.datacache.DataCacheStoreManager.insert(D
    ataCacheStoreManager.java:265)
    at
    com.solarmetric.kodo.runtime.StateManagerImpl.insert(StateManagerImpl
    ..java:1783)
    atcom.solarmetric.kodo.runtime.PNewState.flush(PNewState.java:31)
    at
    com.solarmetric.kodo.runtime.StateManagerImpl.flush(StateManagerImpl.
    java:372)
    at
    com.solarmetric.kodo.runtime.PersistenceManagerImpl.flush(Persistence
    ManagerImpl.java:426)
    at
    com.solarmetric.kodo.ee.EEPersistenceManager.beforeCompletion(EEPersi
    But when I try to execute the statement above against the database
    manually
    everything works fine.
    I'm absolutely desperate!
    P.S. On 2.4.0 RC the operation invoking this database insert completes
    fine.
    "Alexey Maslov" wrote in message
    news:[email protected]...
    Hi!
    When I try to persist object having field of type java.util.Date I
    get
    the
    following SQL logged by Kodo with subsequent transaction rollback:
    2002-11-14 15:03:35,099 INFO
    [com.solarmetric.kodo.impl.jdbc.ee.ManagedConnecti
    onFactoryImpl.supportcrm/kodo] INSERT INTOBILLY.TT_COMMENTS(COMMENT_TYPE,
    TEXT,
    CREATED_BY, ID, SUBJECT, CREATE_DATE, TT_MAIN_ID) VALUES (1, '1',
    10,
    >>>
    279,
    '1',
    {ts '2002-11-14 15:03:35.059'}, 147)
    When I change "{ts '2002-11-14 15:03:35.059'}" with
    "TO_DATE('2002-11-14
    15:03', 'YYYY-DD-MM HH24:MI')" in SQL editor
    and execute it everything works fine.
    What does "{ts '..'}" mean? Is it a SQL generation error?
    Thank you in advance.
    Best regards,
    Alexey Maslov
    Patrick Linskey [email protected]
    SolarMetric Inc. http://www.solarmetric.com
    Best regards,
    Alexey Maslov

  • Which Data Type with 255 cars +

    Hi,
    I have a flat structure table with 15-20 fields, and I need for one of the field a data type with more than 255 cars
    I cant put a STRING without having the flat structure error ...
    Which one should I use ? How should I proceed ?
    Thanks !
    Kr,
    BA

    Hi Benjamin,
    use SE80, click repository info system, click dictionary - data elemets. Chose length > 1024. F8 to execute.
    Check where-used-list of what you like to use to make sure it is so frequently used that SAP will not change it.
    Or better create your own Z data element with required length
    Regards
    Clemens

  • MS Sql + java.util.Date type

    Hi,
    In MySql everything is ok, but in MS Sql I get this error and bouth with timedate type in the database:
    22/11/2006 16:34:59 org.jdesktop.dataset.provider.sql.SQLCommand getUpdateStatement
    WARNING: Problem with update SQL statement null
    22/11/2006 16:34:59 org.jdesktop.dataset.provider.sql.SQLCommand getUpdateStatement
    WARNING: The Java type java.util.Date is not a supported type.
    com.microsoft.sqlserver.jdbc.SQLServerException: The Java type java.util.Date is not a supported type.
    ===========
    My code:
    ===========
    Date newDate = dateReminder.getDate();
    miliSecDate = newDate2.getTime();
    s = spinner.getTime();
    timeStr = s.split(":");
    miliSecTimeS = Long.parseLong(timeStr[1].trim());
    miliSecTime = ((miliSecTimeH * 60 * 60) + (miliSecTimeS * 60)) * 1000;
    newDate2.setTime(miliSecTime + miliSecDate);

    Even if I set myJDatepicker.getDate()
    I get the same error.
    my code:
    GlobalTablesProperties.getInstance().getProvider()
    .getCommand().setParameter("date", myJDatepicker.getDate());
    GlobalTablesProperties.getInstance().getProvider()
    .save(
    GlobalTablesProperties.getInstance().getTaskData());
    JDBCDataConnection jdbcConn = (JDBCDataConnection) (GlobalTablesProperties.getInstance().getProvider().getConnection());
    jdbcConn.commit();
    GlobalTablesProperties.getInstance().getSelectedDataModel()
    .setValue("date", myJDatepicker.getDate());

  • Oracle/java timestamp data type error.. please help

    Im having trouble with a SQL query of mine. Im trying to get a timestamp using JDBC from an oracle database however i get the following error:
    java.sql.SQLException: ORA-00932: inconsistent datatypes: expected %s got %s
    Now when i put the java.util.timestamp into the DB it appears to change.
    When I printout the value of the timestamp in my console it prints the following:
    07-06-26 17:28:09.414
    When i check the value from SQL PLUS it gives me this value
    07-06-26 17:28:09,000000
    Does anyone have any idea why this happens? and more importantly how I can retrieve the timestamp again.
    Im using BEA workshop which means i dont have any means of manipulating the data before presenting to the frontend.
    The database is Oracle 9.2.0.1

    user582245,
    Please provide the following:
    1. Entire error message and stack trace you are getting.
    2. Part of your code where the error occurs.
    3. JDK version you are using.
    4. Oracle data-type of the problematic column.
    Good Luck,
    Avi.

  • Mapping SQL data types (especially SMALLINT) to Java classes

    I want to know the reason for a certain pair of exceptions in JDBC�s mapping of SQL data types to Java classes.
    Sun�s web site ( http://java.sun.com/j2se/1.4.2/docs/guide/jdbc/getstart/mapping.html ), Sybase�s site, and other sites contain mappings from SQL data types to Java primitive data types and/or Java classes. On that Sun web page, Section 9.9.1 maps mostly to Java primitive data types, and Section 9.9.3 maps mostly to Java classes. For the SQL data types that map to both primitive data types and classes, the class is typically the wrapper class of the primitive data type. For example, SQL�s DOUBLE data type maps to both the double primitive data type and its wrapper class (Double). However, Section 9.7 of that Sun web page says that there are exceptions for SQL�s TINYINT and SMALLINT. As expected, they map to the byte and short primitive data types, but they map to the Integer class, not the Byte and Short classes (which are the wrapper classes for byte and short). The web page does not state the reason for this pair of exceptions. It seems to me that SMALLINT data would either work for both short and Short or fail for both short and Short. I don�t see why it would work for short but fail for Short (as the web page implies).
    Can anybody think of a reason for the pair of exceptions? Thanks.

    ghs wrote:
    1) If a DBMS deals with the short and byte primitive data types (as the various web pages imply that it does), then why would it not deal with the Short and Byte wrapper classes?As another guess, because conversions get a little weird in java. Or at least they did in the past. As I recall (with not a lot of clarity) it is possible to do something like pass a perfectly valid string value into a short and get an exception. Whereas using Integer and then converting to Short works.
    Keep in mind that these are guesses.
    3) What I really want to know is this: If I use wrapper classes of Short and Byte (instead of Integer), what will be the harmful consequences (IF ANY)? So far, I have done some trivial testing with a Short for a SMALLINT column (I have not yet tried any TINYINT columns), and it seems to be working.I considered it risky to not test all target databases and drivers.
    Obviously testing will reveal problems.
    If you don't want to test then you might want to stick with integers.

  • Unsigned data types

    I have been using java for many years and never really needed this (which is probably why it's not in java by default), but I am porting a C++ library to java and the C++ code uses quite a bit of WORD (16 bit unsigned) and DWORDs (32 bit unsigned) and a great amout of shifting.
    This is kind of a lame question, but I can't get it to work and I think it is due to the uncontrolable sign bit - does anyone have any resources that can point me in the right direction? Everything on the web just talks about java primitive data type - which I know already - but there is little about using unsigned types or how to port them. Links, books, whatever.
    The project is to get a windows library to work on linux (any everything else) - I have ported it into a gcc C++ and will do JNI if it gets down to it, but I would like to get a native java class going. -- I can't post the code because it's NDAed :(
    Any info, links, books, tips, anything is highly welcome
    Thank you much,
    Rob

    You don't understand my concern (or I misunderstand
    you). A char solution for the 16 bit unsigned type
    (word) is great, but if you're gonna write methods to
    shift a 32 bit dword as a long (ignoring the sign
    bit), why not use that for the 16 bit version as well?I agree, promoting from 16->32 bits or 32-->64 bits sounds like a temporary solution. For "unsigned int"
    I'd just use int and shift with >>> and handle comparisons with either promotion to long or a case analysis
    on sign, which ever works better.
    Let me add, as an old C/C++ programmer I'm glad >99% of the time that Java doesn't have the
    plethora of unsigned types of C/C++ (not to method the ambiguity of 'char' in those languages!).
    And I don't miss those languages dubious promotion rules. Every C book has the puzzler:
    unsigned u = 1;
    if (u < -1) {
       //always true!

  • Poblem with java.sql.Date while inserting to a table

    Hi All,
    I have a PostgreSQL database table which contains fields(columns ) of type date. I want to insert values to the table in the[b] �dd-MMM-YYYY� format using the prepared statement.
    My code is as follows
    java.text.DateFormat dateFormatter =new java.text.SimpleDateFormat("dd-MMM-yyyy");
    String formatedDate=dateFormatter.format(theDate);
    currentDate = new java.sql.Date(dateFormatter.parse(formatedDate).getTime())
    �������������������
    �������������������
    �������������������
    pst.setDate(12,currentDate);The problem is the currentDate variable gives date only in the �YYYY-MMM-dd� format but requirement is the currentDate variable should give date in the �dd-MMM-YYYY� format and this should be save to table as java.sql.Date type
    There is any solution???? please help me...
    Thanks and Regards,
    Hyson_05

    Hi,
    What are you talking about? A Date does always wrap a millisecond value, and doesn't have any formatting. It's the database, or your program which formats the date that you see.
    In short. You should format the value when you print it, and not when you store it.
    Kaj

  • How to convert Date type

    I have a JSP to read the date value and use it to update the corresponding column in the table. In the JSP, the data type returned from request.getParameter("hiredate") is java.util.Date. Unfortunately, the CachedRowSet requires the java.sql.Date type. How can I convert the java.util.Date type to java.sql.Date type? Please advise,thanks.
    SK

    SK,
    This is how I do it:
    java.util.Date utilDate = new java.util.Date();
    long millis = utilDate.getTime();
    java.sql.Date sqlDate = new java.sql.Date(millis);Good Luck,
    Avi.

  • Data Type with reference and view maintenance

    Dear all,
    There are two questions that I want to ask.
    1.     Error when referencing a table with data type = u2018STRINGu2019.
    I have a Z table with some fields = u2018stringu2019, when I use this as a reference, an error prompted.
    "ZTBL_ABC" must be a flat structure. You cannot use internal
    tables, strings, references, or structures as components.-
    2.     Error in generating the View maintenance for field length > 255.
    Actually, I want to create fields with
    1.     data type = char(255),
    2.     data type = text
    3.     data type = char(3000)
    It is okay if I create the field with the selected size, however, when I generate the View maintenance (which can be access through SM30); it does not allow me to do so. It still not working if I change it into string. How can I create such table and use the table maintenance, as well as using that as the reference type of an internal table for another program?
    Regards,
    Mandy Au

    Hello,
    1st of all a table which has a field of type string can be converted in to table maintenance because TM does not support string type as it becomes a very big field to be displayed on screen ... so u need to change that.
    and then about the CHAR of length 3000 is too big ... to have a max limit of 255.
    If you change this both u will be able to generate TM.
    Incase after changing the field length it it gives error in activatin your table then go to SE14 put your table name EDIT and then Adjust n activate it....
    hope this was helpful
    --- Close the post once you get the solution

  • Use java.util.Date in the JMX query

    Hello All
    Anybody know How to write JMX query for finding InstanceObject by attribute that has java.lang.Date type
    Best regards

    Just refer to each class explicitly, through a fully qualified class name as:
    java.util.Date myDate = new java.util.Date();

  • Java data type - byte

    Hi;
    I've a question here, hopefully some one can help me to clear my doubt.
    private byte[] buf = new byte[1024];
    as the declaration done above, does that mean the buf can hold until 1024 bytes data? as i know, byte data type only able to hold +2 power of 8 till -2 power of 7.
    YY.

    private byte[] buf = new byte[1024];
    as the declaration done above, does that mean the buf can hold until
    1024 bytes data? Yep, you've just defined an array of 1024 bytes, all neatly lined up next
    to eachother, the first byte can be retrieved or altered by indexing it like
    this: 'buf[0]', the next one as 'buf[1]' and the last one as 'buf[1023]'.
    as i know, byte data type only able to hold +2 power of 8 till -2 power of 7.Erm, almost; a byte can store any integral number in the range -128 to 127
    inclusive, i.e. -2**7 to 2**7-1.
    kind regards,
    Jos

  • How to use the JE database with other data types than byte arrays?

    Hi! I searched the javadoc of Berkley DB JE, for a way to introduce entry (but I need also retrieve) data with other type than byte arrays, e.g. String, or anything else, as int may be, etc.
    Still, I didn't find any such way, because the main (only?!) method to entry data into an open database - according what I found in javadoc - is:
    "public OperationStatus put(Transaction txn, DatabaseEntry key, DatabaseEntry data) throws DatabaseException"
    and both this and the corresponding method for retrieves, are based on the same DatabaseEntry type, which allow only entry data on byte[] support.
    What if I need to use Strings or int, or even char? I must do a special conversion from these types, to byte[], to use the database?
    Thank you!

    On the doc page (this is also in the download package),
    http://download.oracle.com/docs/cd/E17277_02/html/index.html
    see:
    Getting Started Guide
    Java Collections Tutorial
    Direct Persistence Layer (DPL)
    All of these describe how to use data types other than byte arrays.
    --mark                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Primitive data types as a sequence of bytes

    Does anyone have any experience of converting between primitive data types and sequences (i.e. arrays) of bytes? In particular I want to transmit primitive data types over a socket connection by writing a sequence of bytes.
    Thanks in advance.

    Yes. My personal favourite class for this is java.nio.ByteBuffer though you can also do it with java.io.DataInputStream/DataOutputStream and that might work better with sockets. ByteBuffer is particularly useful with pre-specified formats since you can specify big/little endian storage.

Maybe you are looking for