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?

Similar Messages

  • Converting a byte[] into an int

    I am using the MD5 hash function to create a message digest. When the hash function is complete it returns a byte[]. I want to turn this byte [] into an int, so that I can exclusive or (^) it to a node id according to this traceback algorithm I am trying to implement.
    Basically, I need to turn a byte[] into an int, and then from an int back into a byte[].
    I've looked throughout the forums at different implementations of this, but some do not return the same byte[] as the original, other's have said to use the ByteBuffer, but how do I use it to turn a byte[] into an int?
    Any help would be great, thanks!!!

    Unfortunatly that will not work. As a previousposter
    indicated, you must mask off the lower 8 bits ofeach
    byte after converting to int (or the equivilentmask
    after shifting).Um? Why would the "sign" bit be getting shifted INTO
    the lowest bit?D'oh! Sorry. My bad. When bytes[n] gets "implicitly" cast to do the calculation. Gak! Nevermind.
    Corrected would be:
    iBytesVal = ((bytes[3] & 0xFF) << 24);
    iBytesVal |= ((bytes[2] & 0xFF) << 16);
    iBytesVal |= ((bytes[1] & 0xFF) << 8);
    iBytesVal |= (bytes[0] & 0xFF);

  • Converting a byte array into int

    Here's my problem, I've read my data from a server into a byte array.
    the array is 12 elements in length representing three int variables.
    int flag;
    int query_a;
    int query_b;
    here's what i receive:
    0 0 0 0 34 0 0 -2 21 0 0 0
    how do i convert these into the int values i need.
    i know the first four are for flag = 0, but how does it convert?
    0000 = 0 for each byte
    00000000 00000000 00000000 00000000 = 0 for each bit?
    or is there a method to convert from a byte to int?

    Look at the ByteBuffer class (part of 1.4.1) - before that, you would have had to manually build your integers using left shift and & operator (not that big of a deal, really).
    Be sure you know the "Endian"-ness of the platform you are reading data from though, otherwise, your ints will not be what you expect!
    - K

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

  • How do I convert the unicode into an int?

    I have to take a large integer from user and put each digit into an array. To take the large number I use .nextLine() so that I would be stored as a string. Then I put each digit into an array of type int, and I use implicit type casting to convert each character to an int. The problem is that now the array contains the unicode for the number, how do I get the actual number?
    I know this is kind of silly not to use bigInteger but that's part of the assignment.
    better yet, the array mas as well be of bytes since no digits Unicode goes above 57
    Edited by: bean-planet on Oct 31, 2008 1:12 PM

    So your character is '1' and when you cast that to an int you get something like 49? And you want 1 instead? If that's the case then don't cast, use Character.getNumericValue('1') instead. But read the documentation for the method so you don't get surprised at what Character.getNumericValue("L") returns, for example.

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

  • Why is there only read(byte[]) & not read(int[])

    I'm trying to read large raw images using the RandomAccessFile. Different images are of different types, some are uInt8, some are int8, some are int16, uInt16, float, etc. The only way I know to read them fast enough is by reading an array of bytes, and then putting the bits together into a new array of the desired type, e.g. shifting and adding to the bytes.
    I'm sure there's a clever way to read different types really fast... How?

    Well... Is there any possabilities to create a new
    int[] array that is "pointing" at the same memory
    allocation as the byte[], just as you can do in C or
    other languages with pointers?
    Nope, Java is type safe.
    It would be easy if I could make the compiler
    interpret the byte[] as an int[]... Suggestions?
    Create a java.io.DataInputStream to read from a java.io.ByteArrayInputStream that reads from your byte[] is one option:ByteArrayInputStream byteStream = ByteArrayInputStream(anArrayOfBytes);
    DataInputStream integerStream = new DataInputStream(byteStream);
    int firstInt = integerStream.readInt();
    ...If you need random access to an int array maybe you need to create the array first and the read ints to it...

  • Failed When converting nvarchar value SC1 to int (Cinf)

    Hai,
               In my screen conversion master after entering all the data's if i click addon button the error showing
    Conversion Failed When converting nvarchar value 'SC1' to int (Cinf)
    where SC1 is the object code of my form.
    Can anyone suggest what could be the problem?
    Regards

    Hi Anitha,
    Please check the variable @object_type in the SBO_SP_TransactionNotification stored procedure in your company database. In older versions of SBO, this had an int datatype. In 2007A or 2007B, this should be nvarchar(20) and you will get a conversion error when adding or updating UDO data if the variable is still an int datatype. Please see SAP Note 967470 for more details.
    Kind Regards,
    Owen

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

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

  • Arithmetic overflow error converting expression to data type int

    Hi
        iam creating on sp for  the  database total size , used mb and  free size .  percentage free . 
     in  this purpose i was creating on sps, with in the sp iam was writing  one select statement . it  statement is    
    SELECT [Drivename] ,[DataSizedUsedMB],[DriveFreeSizeMB],DriveTotalSizeMB,
      CAST( (DriveFreeSizeMB/DriveTotalSizeMB)*  100 AS NUMERIC(5,2))
       As
      [PercentFree] ,[DateRecorded] FROM 
    SELECT SUBSTRING([physical_name],1,1) AS Drivename,
      CAST(((SUM(COALESCE(size,0)))*8)/1024 AS NUMERIC(20,2)) AS DriveTotalSizeMB,
      CAST(((SUM( COALESCE( FILEPROPERTY( [name],'SpaceUsed'),0)))*8)/1024 AS NUMERIC(20,2)) AS DataSizedUsedMB,
      CAST(((SUM(COALESCE(size,0))-SUM(COALESCE(fileproperty([name],'spaceused'),0)))*8/1024)AS NUMERIC(20,2)) AS DriveFreeSizeMB
      ,SYSDATETIME()  AS [DateRecorded]
    FROM sys.master_files 
    GROUP BY SUBSTRING([physical_name],1,1))  AS Data
      it was executive one  server with out error  but the same select  statement is writing antoher server iam geeting  belo error.
    "@ErrorDesc: Line 24 - Line 13- Arithmetic overflow error converting expression to data type int." 
      how to slove this issue..
    please help me...

    Change 8 to 8E0, to make it a float literal. The data type of
    SUM(COALESCE(size,0)))*8)
    is int, since all components are int, and it can easily overflow the size for an int. If you use 8E0, you get a float, and the entire expression will be float.
    Erland Sommarskog, SQL Server MVP, [email protected]

  • Arithmetic overflow error converting expression to data type int. Why in this case?

    Hi guys, it is Friday and I am really tired but..
    WITH CTE AS (
    SELECT LEN(CONS_ID) AS PROCA FROM TryCons)
    SELECT SUM(PROCA) FROM CTE
    Why I retrieve
    Arithmetic overflow error converting expression to data type int.
    Len should returns a number and so sum should work. It can be because I am trying to read  500 millions rows? But it wouldn't make sense.. 

    Len should returns a number and so sum should work. It can be because I am trying to read  500 millions rows? But it wouldn't make sense.. 
    If the average length of the field exceeds 4.29, that statement will explode. Since I don't know what's in CONS_ID, I can't say whether it makes sense or not. Although, I will have to say that from my uninitiated position, this seems like an
    accident to happen.
    Erland Sommarskog, SQL Server MVP, [email protected]

Maybe you are looking for

  • No records in UWL for mdm

    Hi all, I have a problem with the UWL for MDM, no records are displayed. I have configured things after all the guides and articles found here on SDN and all connection tests are fine, data is displayed in the iVews. (for Vendors). There are tasks in

  • Suppressing Leading Zero in Date

    We are currently having a problem when running a query in BEX.  The date which displays as MM/DD/YYYY is suddenly displaying with the leading zero in the month and day supressed, for example "3/5/2006" instead of "03/05/2006".  This is interfering wi

  • Used rank mirror script but everyone "connection time-out

    What is going on? I can ping google no problem, but like the subject says everything says "connection time-out" when I try to pacman -Syy or when I try to pacstrap /mnt base base-devel So what is going on?

  • Iphoto cannot open archive

    I am running iphoto 5.0.4 (which I think is the newest version) on OS 10.3.9 (Powerbook 1.5Ghz). When I try to start iphoto, I get a (German, so this is a rough translation) warning: YOU CANNOT OPEN YOUR CURRENT ARCHIVE WITH THIS VERSION OF IPHOTO. Y

  • Can't open Disk Images

    For the past couple of weeks, I've noticed that I'm no longer able to mount Disk Images on my iBook. When I try, I get this message. Of course the name of the image file changes to whatever image it is I'm using. Anyone know what may be causing this?