Converting a byte to an integer

Hi,
I want to convert a byte[] variable called 'rgb' to an integer value. when i looked through the api, i found intValue() could do so i included the statement
int num = rbg.intValue();but it gives me a error. how can i convert the byte[] value to an integer. any suggestion, i am new to Java programming.
Thanks in advance

It would help if you showed a little more of your code--like what rbg is for instance--and if you pasted in the exact error message.
What class was intValue in? You mean the one in the Byte class? That's a method that you call on a Byte object, not a byte[] .

Similar Messages

  • Raw integer in byte format to integer class

    Hi,
    This seemed like an incredibly easy problem to me at first, but for some reason I'm having a lot of trouble with it. I have an integer in byte array format, (byte[] b; the integer is in b[0],b[1],b[2] and b[3], little endian format). Can someone write a function real quickly to do this properly? I'm specifically having trouble when the byte in b[0] is a negative number, because when I add it to the integer that I have, the integer comes out negative.

    I found the solution to my problem. It's as easy as taking the bytes and using 0xff&b[x] before you use them. This has the effect of converting them to unsigned bytes.

  • Convert a byte/Byte - HEX STRING ?

    Hi ,
    My Problem is , I want to convert a byte/Byte value to hex string. If there is any way to convert bytes to hex strings then please tell me.
    please help me.

    Integer.toHexString(byteValue);
    http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Integer.html

  • How do I convert a doule to an integer?

    How do I convert a doule to an integer? I know how to do the reverse, but I don't know how to do it backwards. TIA!

    Err, I meant "double," not "doule." It's getting late. -_-                                                                                                                                                                                                       

  • Convertion of byte array in UTF-8 to GSM character set.

    I want to convert byte array in UTF-8 to GSM character set. Please advice How can I do that?

    String s = new String(byteArrayInUTF8,"utf-8");This will convert your byte array to a Java UNICODE UTF-16 encoded String on the assumption that the byte array represents characters encoded as utf-8.
    I don't understand what GSM characters are so someone else will have to help you with the second part.

  • Can't convert int to java.lang.Integer.

    Hi everyone.
    I'm working on an auction site at the moment and have problems gaining a bidID number. This is part of my code and my error.
    AuctionFacade aHse = (AuctionFacade) application.getAttribute("AuctionFacade");
    String strTraderName = (String)session.getAttribute("traderName");
    String strPassword = (String)session.getAttribute("password");
    String strIDNum = request.getParameter("auctionID");
    Integer intID = Integer.valueOf(strIDNum);
    Integer [] bids = aHse.getAllBids(intID);
    float fltYourBid = aHse.getBidPrice(bids.length);
    ^
    Can't convert int to java.lang.Integer.
    can anyone help please?

    So, does "aHse.getBidPrice" expect an int or an Integer as its parameter? And does it return an int, or an Integer, or what? The answer to those questions may lead to your solution -- look at what you are actually using as the parameter, for example.

  • System.InvalidCastException: Operator ' =' is not defined for type 'Byte()' and type 'Integer'.

    I'm getting the following error
    System.InvalidCastException: Operator '>=' is not defined for type 'Byte()' and type 'Integer'.
       at Microsoft.VisualBasic.CompilerServices.Operators.InvokeObjectUserDefinedOperator(UserDefinedOperator Op, Object[] Arguments)
       at Microsoft.VisualBasic.CompilerServices.Operators.InvokeUserDefinedOperator(UserDefinedOperator Op, Object[] Arguments)
       at Microsoft.VisualBasic.CompilerServices.Operators.CompareObjectGreaterEqual(Object Left, Object Right, Boolean TextCompare)
       at Customer_Fee_Calculator.Form1.GetCost2(Object dimension) in C:\Users\Chris\Documents\Visual Studio 2013\Projects\Customer Fee Calculator\Customer Fee Calculator\Form1.vb:line 259
       at Customer_Fee_Calculator.Form1.CustomerSelect_SelectedIndexChanged(Object sender, EventArgs e) in C:\Users\Chris\Documents\Visual Studio 2013\Projects\Customer Fee Calculator\Customer Fee Calculator\Form1.vb:line 72
                Dim inotes = rs1("INOTES").Value
      (Line 72)          If inotes.Length > 1 Then
                    cost = GetCost2(rs1("INOTES").Value)(0)
                    desc = GetCost2(rs1("INOTES").Value)(1)
                Else
                    PkgType = CInt(rs1("PKGTYPE").Value)
                    cost = GetCost(PkgType)(0)
                    desc = GetCost(PkgType)(1)
                End If
     Function GetCost2(dimension)
            Dim tempSql1, rs1
            Dim MyResult As New ArrayList
            Select Case dimension
    (line 259)            Case 1 To 24
                    tempSql1 = "SELECT * FROM PRODUCT WHERE PRODUCTID = 13"
                Case 25 To 43
                    tempSql1 = "SELECT * FROM PRODUCT WHERE PRODUCTID = 14"
                Case 44 To 71
                    tempSql1 = "SELECT * FROM PRODUCT WHERE PRODUCTID = 16"
                Case 72 To 120
                    tempSql1 = "SELECT * FROM PRODUCT WHERE PRODUCTID = 17"
                Case 121 To 499
                    tempSql1 = "SELECT * FROM PRODUCT WHERE PRODUCTID = 18"
                Case 500
                    tempSql1 = "SELECT * FROM PRODUCT WHERE PRODUCTID = 19"
                Case Else
                    tempSql1 = "SELECT * FROM PRODUCT WHERE PRODUCTID = 14"
            End Select
            rs1 = dbconnect(tempSql1, 1)
            MyResult.Add(rs1("RETAIL1").Value)
            MyResult.Add(rs1("DESCRIPTION").Value)
            MyResult.Add(rs1("PRODUCTID").Value)
            rs1 = Nothing
            tempSql1 = Nothing
            Return MyResult
        End Function

    Chris,
    I'm not a database guy - so in many ways, I'm not really qualified to answer this, but I'll make a suggestion anyway:
    At the very top of your code, put the following:
    Option Strict On
    Option Explicit On
    Option Infer Off
    With strict on and infer off, it will force you declare types - which I see missing in many places in the code.
    It's entirely possible that by you then going through and fixing those issues, you'll have corrected the problem.
    I don't know that, but it's possible -- and it should be done this way anyway, so there's certainly no harm to be done; in fact you'll actually speed up the program to a small degree because objects don't have to be inferred for the type that they actually
    are.
    ***** EDIT *****
    Also this: DON'T declare any of the types simply as "Object"; that's just trading off late binding for boxing, so you haven't really done much good. Declare them each as their correct actual type.
    Still lost in code, just at a little higher level.

  • FM to convert double byte chars

    Hi All,
    Is there anyone know what are the function module to convert double-byte chars? Thanks.

    Seems like Blue Sky is not clear
    You want to convert what into what?
    Whats the purpose of this requirement, kindly give more details.
    Regards
    Karthik D

  • How Convert a Byte array to a image format

    Hi,
    How to convert a Byte array to an image format....I shall be more clear what i want...See i recieve a Byte array fom server this Byte array before recieveing at my end it was converted from an image/text format into a Byte array and is sent from server and, I recieve this Byte array now I have to convert this Byte array into their respective image....please tell me how to convert a Byte array to a image ......... Kindly explain clearly as i am new to Java......
    Thanking You.

    Note: This thread was originally posted in the [New To Java|http://forums.sun.com/forum.jspa?forumID=54] forum, but moved to this forum for closer topic alignment.

  • Converting a byte[] into a char[]

    Hi All,
    what's the best way to convert a byte[] into a char[]?
    Any advice appreciated. Thanks in advance.

    you will need a encoding schema...
    byte is binary data, char is interpret from byte by the system...
    easiest way without extra coding...
    new String(byte[], encoding).toCharArray()
    if you don't specify encoding... system default is used.

  • Converting a byte[] back to key problem

    I CAN create a key and convert the key to a byte array, then convert the array to a string(base 64):
    KeyGenerator generator = KeyGenerator.getInstance("DES");
    generator.init(new SecureRandom());
    key = generator.generateKey();
    byte[] keyBytes = key.getEncoded;
    BASE64Encoder encoder = new BASE64Encoder();
    String randomKey = encoder.encode(keyBytes);
    and I CAN save that string to a database, forget about it, then sometime later reload it and convert it to a byte array again:
    String loadedKey = "WhAt3Ver-It-I5" //from DB
    BASE64Decoder decoder = new BASE64Decoder();
    byte[] loadedKeyBytes = decoder.decodeBuffer(loadedKey);
    what I CAN'T do is convert the loadedKeyBytes back into the key of the same type as it was originally, enabling me to decrypt whatever that key originally encrypted.
    Does anyone know.
    I know I need to convert it to a KeySpec, I presume as:
    DESKeySpec keySpec = new DESKeySpec(loadedKeyBytes);
    this compiles correctly.... but how do i then recreate the key so i can use it for decryption.
    Once i've finished this test program I should be able to port it to my application.
    Many thanks in advance guys!
    Cheers!
    Relisys
    ================ CODE FOLLOWS ======================
    import java.io.*;
    import java.security.*;
    import java.security.spec.*;
    import javax.crypto.*;
    import javax.crypto.spec.*;
    import com.sun.crypto.provider.SunJCE;
    import sun.misc.*;
    public class SecPrescrip {
    public static void main(String[] args) throws Exception {
    // Create Key.
    Key key;
    KeyGenerator generator = KeyGenerator.getInstance("DES");
    generator.init(new SecureRandom());
    key = generator.generateKey();
    // Get a cipher object
    Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
    // Encrypt the input string:
    cipher.init(Cipher.ENCRYPT_MODE, key);
    String input = "Medicare Secure Prescription: 30 Tamazopan 200mg tablets. Dosage: 1 to be taken every 4 hours";
    System.out.println("Stage 1: ENCRYPT PRESCRIPTION WITH A RANDOM DES KEY");
    System.out.println("===================================================");
    System.out.println(" - Input Plain Text: "+input);
    System.out.println("");
    byte[] stringBytes = input.getBytes("UTF8");
    byte[] raw = cipher.doFinal(stringBytes);
    BASE64Encoder encoder = new BASE64Encoder();
    String ciphertext1 = encoder.encode(raw);
    System.out.println(" - Cipher Text: "+ciphertext1);
    System.out.println("");
    byte[] keybytes = key.getEncoded();
    String randomkey = encoder.encode(keybytes);
    System.out.println(" - Random Prescription Key: "+randomkey);
    System.out.println("");
    System.out.println("ENCRYPTION SUCESSFULL");
    System.out.println("");
    System.out.println("");
    System.out.println("Stage 2: ENCRYPT RANDOM KEY WITH PATIENT MEDICARE KEY");
    System.out.println("=====================================================");
    BASE64Decoder decoder = new BASE64Decoder();
    String passphrase = "ABCD1234efghIJ56"; //Patient Medicare Key
    System.out.println(" - Patient Medicare Key: "+passphrase);
    System.out.println("");
    System.out.println(" - Input Plain Text: "+randomkey);
    String algorithm = "PBEWithMD5AndDES";
    byte[] salt = new byte[8];
    int iteration = 20;
    KeySpec ks = new PBEKeySpec(passphrase.toCharArray());
    SecretKeyFactory skf = SecretKeyFactory.getInstance(algorithm);
    SecretKey key2 = skf.generateSecret(ks);
    byte[] input2 = decoder.decodeBuffer(randomkey);
    MessageDigest md = MessageDigest.getInstance("MD5");
    md.update(passphrase.getBytes());
    md.update(input2);
    byte[] digest = md.digest();
    System.arraycopy(digest, 0, salt, 0, 8);
    AlgorithmParameterSpec aps = new PBEParameterSpec(salt, iteration);
    cipher = Cipher.getInstance(algorithm);
    cipher.init(Cipher.ENCRYPT_MODE, key2, aps);
    byte[] outputFinalKey = cipher.doFinal(input2);
    String ciphertext2 = encoder.encode(outputFinalKey);
    String saltString = encoder.encode(salt);
    String encryptedCiphertext = saltString+ciphertext2;
    System.out.println("");
    System.out.println(" - Cipher Text (Final Prescription Key): "+ciphertext2);
    System.out.println("");
    System.out.println(" - Salt: "+saltString);
    System.out.println("");
    System.out.println(" - Full Encrypted Output: "+encryptedCiphertext);
    System.out.println("");
    System.out.println("ENCRYPTION SUCESSFULL");
    System.out.println("");
    System.out.println("");
    System.out.println("Stage 3: DECRYPT PRESCRIPTION KEY USING PATIENT MEDICARE KEY");
    System.out.println("============================================================");
    //NOT CHANGED String passphrase = "ABCD1234efghIJ56";
    System.out.println(" - Patient Medicare Key: "+passphrase);
    System.out.println("");
    System.out.println(" - Input Plain Text: "+ciphertext2);
    algorithm = "PBEWithMD5AndDES";
    salt = new byte[8];
    iteration = 20;
    ks = new PBEKeySpec(passphrase.toCharArray());
    skf = SecretKeyFactory.getInstance(algorithm);
    SecretKey key3 = skf.generateSecret(ks);
    //Load in the input bytes as if they had been loaded from an sql database or the like
    String saltIn = encryptedCiphertext.substring(0,12);
    String ciphertext3 = encryptedCiphertext.substring(12,encryptedCiphertext.length());
    byte[] saltArray = decoder.decodeBuffer(saltIn);
    byte[] ciphertextarray = decoder.decodeBuffer(ciphertext3);
    aps = new PBEParameterSpec(saltArray, iteration);
    cipher = Cipher.getInstance(algorithm);
    cipher.init(Cipher.DECRYPT_MODE, key3, aps);
    byte[] outputKey2 = cipher.doFinal(ciphertextarray);
    String plaintext2 = encoder.encode(outputKey2);
    System.out.println(" - Plain Text (Random Generated Key): "+plaintext2);
    System.out.println("");
    System.out.println("");
    System.out.println("ENCRYPTION SUCESSFULL");
    System.out.println("");
    System.out.println("");
    System.out.println("Stage 4: DECRYPT PRESCRIPTION KEY USING PATIENT MEDICARE KEY");
    System.out.println("============================================================");
    // The decrypter string plaintext should be the same as the BASE64 Encoded representation of the random DES string
    byte[] randomKeyFetched = decoder.decodeBuffer(plaintext2);
    generator = KeyGenerator.getInstance("DES");
    DESKeySpec keyspec = new DESKeySpec(randomKeyFetched);
    * Stuck here! Once the key is reformed it will be complete!
    }

    You need to use a SecretKeyFactory to convert the byte array back to a SecretKey to use in decryption. Continuing your example:
    SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
    DESKeySpec desKeySpec = new DESKeySpec(loadedKeyBytes);
    SecretKey sk = skf.generateSecret(desKeySpec);
    Use sk in the call to the Cipher init() function. (Note that you don't call KeyGenerator to restore a key from its bytes.)
    Incidently, if you're using ECB mode for encryption I don't think you need to worry about the Initialization Vector. However, if you're using CBC mode (which is the default DES mode for the default SunJCE provider), I believe you also have to make sure that the decryption system starts from the same Initialization Vector that was used for encryption. To deal with this, if 'cipher' is your encryption Cipher object, then you call
    byte bytIV[] = cipher.getIV();
    to get the 8-byte IV array. To decrypt, you need to call:
    IvParameterSpec iv = new IvParameterSpec(bytIV);
    This is an AlgorithmParameterSpec, and can be used as the third argument to the init() function for Cipher to set up decryption, e.g.
    Cipher cd = Cipher.getInstance("DES/ECB/PKCS5Padding");
    cd.init(Cipher.DECRYPT_MODE, sk, iv);
    I believe that CBC mode is more secure than ECB mode when you have more than 8 bytes of material to encode (e.g. use "DES/CBC/PKCS5Padding"
    when you create the Cipher objects).
    To simplify things a bit, you might just want to use a fixed 8-byte Initialization Vector by constructing a IvParameterSpec and using it for all DES encryption and decryption.
    The documentation on all of this is extraodinarily obscure.

  • Converting a byte[] to a int or a Point

    I have sent a DatagramPacket containing a Point object converted to a byte[]. Now I want to convert the byte[] object back to a Point object. How do I do it?
    In my application I want to draw a number of dots in a window, send to a copy of the application in some other location on the Net and the two applications must view the same dots in real time. So I thought I would draw the dots, send the cordinats in a Datagram and then draw the dots using this cordinats. Is that a good idea?
    Best regards
    Jonas

    To create a Point from a byte[], assuming the byte[] has two elements:
    Point p = new Point((int)byte[0], (int)byte[1]);Is that what you need?

  • Converting a String to an integer?

    i need to convert a string to an integer..i searched through the site but i didn't find anything...
    Is this conversion possible?

    You didn't look very hard - it's right in the javadocs:
    String s = "44";
    int x = Integer.parseInt(s);I'll leave the exception handling for you.

  • Converting a string to an integer value

    How can I convert a string to an integer?

    sorry, not "of new Integer.." but "or new Integer(.."
    Message was edited by:
    s-e-r-g-e

  • CONVERT 4 bytes WCHAR_T in SOLARIS COMPILER TO UNSIGNED SHORTTO

    All,
    Do you guys know any code or function that could convert 4-bytes wchar_t string literal (Solaris defined 4 bytes for wchar_t) to array of unsigned short?

    Unlike MSFT Windows VC++/C#/VB where you will get UCS-2/UTF-32 when your program has UNICODE macro defined at the start of your source program, POSIX defines wchart as an opaque data type.
    Solaris is a POSIX system and thus we treat the wchar_t also as an opaque data type that can be different from one locale to another.
    (We didn't have Unicode or at least it wasn't that popular when there was wchar_t data type and intefaces first created and also implemented at various Unix systems even though Sun was a founding member company of the Unicode consortium.)
    We though guarantee that the wchar_t will be in UTF-32 for all Solaris Unicode/UTF-8 locales.
    Hence, to have proper conversions between any codeset/codepage or the codeset of the current locale, i.e., nl_langinfo(CODESET), and UTF-32 or UCS-4, please use iconv(3C), iconv(1), or sdtconvtool(1) and such conversion interfaces. By the way, UCS-4 is being obsoleted and so using of UTF-32 is recommended.
    The iconv code conversions between UTF-32 and any other codesets in Solaris will also screen out any illegal characters or byte sequences as specified in the latest Unicode Standard and UTF-8 Corrigendum at Uniocde 3.1 and 3.2.

Maybe you are looking for