Converting from unsigned int / short to byte[]

Can anybody help me, I am trying to convert from:
- unsigned int to byte[]
- unsigned short to byte[]
I will appreciate your help lots. thanks.

@Op.
This code converts an integer to a byte[], but you have to consider the byte order:
        int value = 0x12345678;
        byte[] result = new byte[4];
        for (int i=3; i>=0; i--) {
            result[i] = (byte)(value & 0xff);
            value = value >> 8;
        }This is another option:
        int dummy = 7;
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        os.write(dummy);
        byte[] bytes = os.toByteArray();Kaj

Similar Messages

  • No warning when assigning to an unsigned char from unsigned int

    Is this an error in VC++, or am I missing something?  The following code should give two warnings for assigning to a smaller type, but only gives one: (compiled as 32 bit)
    unsigned
    char c;
    unsigned
    int i = 24;
    // 32 bit unsigned integer
    unsigned
    long L = 25;
    // Also a 32 bit unsigned integer
    c = L; // Warning C4244
    c = i; // no warning
    This happens in Visual Studios 2005, 2010, 2012, 2013 and 2015, at least.

    Is this an error in VC++, or am I missing something?  The following code should give two warnings for assigning to a smaller type, but only gives one: (compiled as 32 bit)
    unsigned
    char c;
    unsigned
    int i = 24;
    // 32 bit unsigned integer
    c = i; // no warning
    This happens in Visual Studios 2005, 2010, 2012, 2013 and 2015, at least.
    Have you tried it with Warning Level 4?
    In VC++ 2008 Express and W4 I get:
    Warning 2 warning C4244: '=' : conversion from 'unsigned int' to 'unsigned char', possible loss of data
    - Wayne

  • Convert from int to char

    Hi,
    How can I convert from an int to char?

    The challange is to convert from int to String without using any API or automatic conversionWoah, what a challenge ! Why ?
    Anyway, what about a recursive call and switch statement. Something likepublic String intToString(int n) {
        if(n<0) {
            return "-"+intToString(-n);
        if(n<10) {
            return getStringDigit(n);
        else {
            return intToString(n/10) + getStringDigit(n%10);
    private String getStringDigit(int n) {
        switch(n) {
            case 0:
                return "0";
            // etc.
    }

  • Wrtie unsigned char and unsigned int into a binary file

    Hi, I need write some data into some specific file format (.ov2) for other applications to read.
    Here is the requirement of the data:
    First byte: An unsigned char value, always "2" means simple POI entry
    Next 4 byte: An unsigned int value,
    Next 4 byte: A signed integer value.
    Next 4 byte: A signed integer value
    then next : A zero-terminated Ascii string
    Here is my code:
                       String name = "name";
                       byte type = 2;
                     int size = name.length() + 13 +1; //1+4+4+4 and there is a 0 at last
                     int a = 1;
                     int b =2;
                     ds.writeByte(type); //1 byte, need save it as unsigned char
                         ds.writeInt(size); //4 //need to be an unsignged int
                         ds.writeInt(ilont); //4 //signed int
                         ds.writeInt(ilatt); //4 //signed int
                         //write zero-terminated ascii string
                         for(int n=0; n<name.length(); n++){
                              ds.writeByte(name.charAt(n));
                         ds.writeByte(0);                    This code could not get the correct result and I think I must do some sign to unsign conversion, but I don't know how to do it. Any help?
    Thanks for you attention.

    You don't have to do anything special at all. What's in a int or a byte is what you, as a programmer, say it is. Java treats int's as signed but, in fact, with 2's complement arithmatic most operations are exactly the same. Load and store, add and subtract - it makes no difference whether a variable is signed or unsigned. It's only when you convert the number, for example to a wider type or to a string representation that you need to know the difference.
    When you read an unsigned byte and you want to widen it to an integer you have to clip the top bytes of the integer e.g.
    int len = input.get() & 0xff;This is because, since java sees a byte as signed it will extend the sign bit into the top bytes of the int. "& 0xff" forces them to zero.
    Writing it, you don't have to do anything special at all - it will autmatically get clipped. The above is probably the only concesion you'll ever need to make to unsigned binary. (You'd need to do the same thing from unsigned int to long, but this almost never happens).
    When I read ov2 files I used a mapped byte buffer, because it allows you to set either big-endian or little-endian and I wasn't sure which ov2 files used. (Sorry, I've forgotten).

  • Trying to understand the details of converting an int to a byte[] and back

    I found the following code to convert ints into bytes and wanted to understand it better:
    public static final byte[] intToByteArray(int value) {
    return new byte[]{
    (byte)(value >>> 24), (byte)(value >> 16 & 0xff), (byte)(value >> 8 & 0xff), (byte)(value & 0xff) };
    }I understand that an int requires 4 bytes and that each byte allows for a power of 8. But, sadly, I can't figure out how to directly translate the code above? Can someone recommend a site that explains the following:
    1. >>> and >>
    2. Oxff.
    3. Masks vs. casts.
    thanks so much.

    By the way, people often introduce this redundancy (as in your example above):
    (byte)(i >> 8 & 0xFF)When this suffices:
    (byte)(i >> 8)Since by [JLS 5.1.3|http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#25363] :
    A narrowing conversion of a signed integer to an integral type T simply discards all but the n lowest order bits, where n is the number of bits used to represent type T.Casting to a byte is merely keeping only the lower order 8 bits, and (anything & 0xFF) is simply clearing all but the lower order 8 bits. So it's redundant. Or I could just show you the more simple proof: try absolutely every value of int as an input and see if they ever differ:
       public static void main(String[] args) {
          for ( int i = Integer.MIN_VALUE;; i++ ) {
             if ( i % 100000000 == 0 ) {
                //report progress
                System.out.println("i=" + i);
             if ( (byte)(i >> 8 & 0xff) != (byte)(i >> 8) ) {
                System.out.println("ANOMOLY: " + i);
             if ( i == Integer.MAX_VALUE ) {
                break;
       }Needless to say, they don't ever differ. Where masking does matter is when you're widening (say from a byte to an int):
       public static void main(String[] args) {
          byte b = -1;
          int i = b;
          int j = b & 0xFF;
          System.out.println("i: " + i + " j: " + j);
       }That's because bytes are signed, and when you widen a signed negative integer to a wider integer, you get 1s in the higher bits, not 0s due to sign-extension. See [http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#5.1.2]
    Edited by: endasil on 3-Dec-2009 4:53 PM

  • Leading Zeroes are lost when convert from string to int

    What I'm trying to do is simple yet the solution has seemed difficult to find.
    I have a system that requires 4 digit numbers as "requisitionNo". The system uses JSPs and accepts the 4 digit number that the user inputs (fyi - duplicate handling is already managed). The input number (rNumber) is of STRING type and in the action (using struts) is converted to an int:
    int requisitionNo = Integer.parseInt(rNumber);At that very line the issue is that when the user inputs a number with leading zeros such as: "0001" the 3 leading zeros are chopped off in the INT conversion. The application validation kicks in and says: "A 4 digit number is required" which is by design. The work around has been that the user has been putting in number that start with 9's or something like that, but this isn't how the system was intended to be used.
    How do I keep the leading zeroes from being lost instead of saving a number "1" to the database how do I keep it saving "0001" to the database? Would I just change everything to STRING on down to the database? or is there another number type that I can be using that will not chop off the leading zeroes? Please provide short code references or examples to be more helpful.

    Yeah, I have to agree here that leading zeroes make no sense. I figured that out when I started to look into this problem. The only requirement that exists is that the user wants it to be a 4 digit number due to some other requirement they have themselves.
    So what I'm gathering from what I've read in the responses thus far is that I should change the validation a bit to look at the STRING for the 4 required digits (which are really 4 characters; maybe I should add CLIENT side numeric validation; currently its doing server side numeric/integer validation; or maybe change up the server side validation instead???) and if they are ALL GOOD then let the application save the int type as it wants to. IE: Let it save "0001" as just "1" and when I come back to DISPLAY this saved number to the user I should append the string of "000" in front of the 1 for display purposes only? Am I understanding everyone correctly?

  • Convert from String to Int

    Hi,
    I have a question.
    How do I convert from String to Integer?
    Here is my code:
    try{
    String s="000111010101001101101010";
    int q=Integer.parseInt(s);
    answerStr = String.valueOf(q);
    catch (NumberFormatException e)
    answerStr="Error";
    but, everytime when i run the code, i always get the ERROR.
    is the value that i got, cannot be converted to int?
    i've done the same thing in c, and its working fine.
    thanks..

    6kyAngel wrote:
    actually it convert the string value into decimal value.In fact what it does is convert the (binary) string into an integer value. It's the String representation of integer quantities that have a base (two, ten, hex etc): the quantities themselves don't have a base.
    To take an integer quantity (in the form of an int) and convert it to a binary String, use the handy toString() method in the Integer class - like your other conversion, use the one that takes a radix argument.

  • Convert from int to String

    Hi, may i know how to convert from int to String??
    For instance, i've>>
    int i = 0;
    i++;
    String temp = i.toString();
    [Need to convert the int to String here. Am i doing the convertion correctly?? Pls correct me. Thanks!]

    Hi, may i know how to convert from int to String??
    For instance, i've>>
    int i = 0;
    i++;
    String temp = i.toString();
    [Need to convert the int to String here. Am i doing
    the convertion correctly?? Pls correct me. Thanks!]String temp = "" + i;

  • Why does the Java API use int instead of short or byte?

    Why does the Java API use int if short or even byte would be sufficient?
    Example: The DAY_OF_WEEK field in Calendar uses int.

    One of the point is, on the benchmark tests on Java performance, int does far better than short and byte data types.
    Please follow the below blog talks about the same.
    Java Primative Speed
    -K

  • How to Convert array of int into array of byte - please help

    I have a 2-dim array of type int and I want to convert it to an array
    of byte. How can I do that? Also, if my 2-dim int array is one dimention
    can I use typecast as in the example below?
    private byte[] getData()
    byte []buff;
    int []data = new int[5];
    //populate data[]
    buff = (byte[]) data; <---- CAN I DO THIS??????
    return buff;

    hi, I suggest you make an array of byte arrays
    --> Byte[][] and use one row for each number
    you can do 2 things,
    take each cipher of one number and put one by one in each column of the row correspondent to that number. of course it may take too much room if the int[] is too big, but that is the easiest way I think
    the other way is dividing your number into bitsets(class BitSet) with sizes of 8 bits and then you can save each bit into each column of your array. and you still have one number in each row. To put your numbers back use the same class.
    Maybe someone has an easier way, I couldnt think of any.

  • Convert from char* to unsigned char*

    Hi, I try compile example from: http://download-uk.oracle.com/docs/cd/B19306_01/appdev.102/b14294/relational.htm#i1000940
    in Visual C++ and I have problem with:
    const string userName = "SCOTT";
    because string is defined as unsigned char* and "SCOTT" is char*, is any function to convert from type char* to type unsigned char* ?

    I'm apologize for this stupid question, answer is very easy:
    const string userName = (const unsigned char*) "SCOTT";

  • Question on converting an int to 4 byte array

    Hello all. I apologize in advance if this information is readily available, because I haven't been able to find a definitive answer to this question. I need to convert an int to a big endian 4 byte-array. I have the following code, which I'm fairly sure works, but it's the big endian part I'm not sure about. Can anyone confirm that this code snippet will do what I expect:
    public static final byte[] intToByteArray(int value)
        return new byte[]
            (byte)(value & 0xff),
            (byte)(value >> 8 & 0xff),
            (byte)(value >> 16 & 0xff),
            (byte)(value >>> 24) };
    }Thank you very much in advance for your help.
    -Kennedy

    kook04 wrote:
    Hello all. I apologize in advance if this information is readily available, because I haven't been able to find a definitive answer to this question. I need to convert an int to a big endian 4 byte-array. I have the following code, which I'm fairly sure works, but it's the big endian part I'm not sure about. Can anyone confirm that this code snippet will do what I expect:The best way is to test it for yourself.
    int i = 0xAABBCCDD;
    byte[] bytes = intToByteArray(i);
    if (bytes[0] == (byte)0xAA && bytes[1] ... etc.) {
      System.out.println("Success!");
    else {
      System.out.println("Oops!")
    }

  • How to convert from java.lang.Integer to int

    Could you please show me
    how to convert from java.lang.Integer to int?
    and how to convert from java.lang.Integer to String?
    Thanks,
    Minh

    Could you please show me
    how to convert from java.lang.Integer to int?
    and how to convert from java.lang.Integer to String?Tip: always keep a browser open on the API docs; if you've got a
    couple of MBs to spare, download the docs; it's very convenient.
    kind regards,
    Jos

  • Converting unsigned to java signed byte value

    Hey ,
    i need to use a raw address in a client i am writing but, of course, the address contains a byte outside of the java signed byte range. if any one could tell me what an unsigned byte of 224 in signed java is i would be very grateful, if you could also show how you did this it would be appreciated. thank you =)

    Re: Converting unsigned to java signed byte value
    i need to use a raw address in a client i am writing
    but, of course, the address contains a byte outside
    of the java signed byte range.
    if any one could tell
    me what an unsigned byte of 224 is in signed java
    I would be very grateful, if you could also show how
    you did this it would be appreciated. thank you =)You misunderstand signed/unsigned.
    A byte has 8 bits. It can represent 256 different values.
    Viewed as an unsigned scalar the range is [0;255].
    Viewed as a signed two's-complement scalar the range is [-128;127].
    Values [0;127] are obviously the same byte values in the two views.
    What the other half of the possible byte values represent depends on what view you adopt.
    You don't need to convert anything.
    public final class Byte224 {
        static byte[] byteArray = {
            (byte)224, (byte)'\n'
        public static final void main(final String[] arg) {
            System.out.println("0x"+Integer.toHexString(byteArray[0]&0xff));
            System.out.println(Integer.toString(byteArray[0]&0xff));
    }

  • Exp/imp, convertion from byte to char.

    Hi,
    I have a dump file exported from a database with nls_lenght_sematics=BYTES. When i import it into a database with nls_lenght_sematics=CHAR, it is retaining the BYTE charecteristics. Is there any way to change it into CHAR while importing. This for globalization support.
    Thanks
    Muneer

    Hi Muneer,
    No, import always preserve the LENGTH semantics of the original columns.
    The workaround is to create your schema objects in the traget database first, with the desired semantics, prior to the importing the data.
    Nat

Maybe you are looking for

  • Macbook pro 15" retina, display flickers, weird lines follow cursor

    Just got this MacBook Pro on Christmas... Installed Microsoft Office Suite, Adobe Photoshop, and Adobe Illustrator today. Later in the day the display became very discolored; vertical and horizontal "shaded" lines follow the cursor, areas above open

  • IPhone4 to Apple TV movie streaming problem

    Movies recorded using my iPhone stream no problem to Apple TV via Airplay but movies that have been downloaded seperately and loaded onto my iPhone and are stored in my iPod part of the iPhone do not have the Airplay icon to allow streaming. Any idea

  • JSP Dynpages

    I created a JSP Dynpage via NWDS. based on the sampples at <a href="http://help.sap.com/saphelp_nw04/helpdata/en/19/4554426dd13555e10000000a1550b0/frameset.htm">SAP Help Creating the JSPDynPage</a> When I run it, I got the error: Error in parsing tag

  • Substituting G/L account

    Hello, i need to replace the G/L account for indirect costs when creating the invoice. The default account for indirect costs is defined in OBYC, say acct XXXXXXXX. Based on PO type, accounts AAAAAAAA or BBBBBBBB must be charged. I've used the substi

  • Project systems integration with portal (EP)

    Dear all, I have to integrate the projects systems module with Portal.(EP) In portal transactional I views can be used to create projects which can be store in the R/3. Now the issue is to create projects with out using Transactional I views. This sh