Array of bytes of length / 2147483648L

I'm receiving bytes from the network and try to convert the 8 bytes in a long, using the following:

static long bytesToLong(byte [] b) throws Exception{
        long result=0L;
        if(b.length!=8) throw new Exception ("Not 8 bytes!");
        for(int i=0;i<4;i++){
            result|=(b[i]&0xff)<<(3-i)*8;
        }
        result<<=32;
        for(int i=4;i<8;i++){
            result|=(b[i]&0xff)<<(7-i)*8;
        }
        return result;
}

It works fine on the Simulator, but on the actual device, I have problems with the 2 ^ 32 bits.

I tested the method with L 2147483648, i.e. 1 followed by 31 zeros (10000000000000000000000000000000).

byte[] c={0,0,0,0,(byte)128,0,0,0};
System.out.println(Function.bytesToLong(c));

but the method has returned-2147483648 L. Why?

No idea, I think that there are a few whole calculation going on in there, probably on this line:

result<>

I couldn't be bothered looking at it because it looked really messy.  Here is a variation that I think works OK.  I know that it works correctly on these values, that I tested, which crashes on the original:

Byte [] c = {0,0,0,0, (bytes) 128,0,0,0};

Byte [] d = {0x7f, 0x7f, 0x7f, 0x7f, (byte) 128, 0x7f, 0x7f, 0x7f};

There are some possible in this code optimization if you use it a lot.

It is possible that I did not interpret your code of origin properly, if so, please let me know.

static long bytesToLong2(byte [] b) {
        if(b.length!=8) throw new RuntimeException ("Not 8 bytes!");
        long result=0L;
        for(int i=0;i<8;i++){
            result = result << 8;
            result = result | 0x000000FF&b[i];
        }
        return result;
}

Tags: BlackBerry Developers

Similar Questions

  • What is the best way to convert an array of bytes or string cluster

    I am writing a program that sends UDP packets and I defined the data I want to send via large groups (with numbers of u8, u16/u32, u16/u8/u32 tables and nested groups). Just before sending the data, I need to convert groups or chains of arrays of bytes. The flatten the string function is almost perfect for this. However, it is addition of lengths in the tables and strings that makes this unusable method, because as far as I can tell.

    As I have many of these groups, I would rather not hard code the unbundle names and conversion/cast of strings or arrays of bytes for each of them.

    Y at - it a function, or a tool that I'm on?

    Thank you!

    mkirzon wrote:

    The program I'm developing is to communicate and to poll an external device that includes a Protocol well documented. The messages that I built in clusters contain components accurate that expected from the other device. So, if my program adds any additional info (such as this array/string lengths), monitor the device external won't recognize messages and returns an error.

    Unfortunately, you have to ungroup your cluster and collect the individual channels to concatinate.

  • Array of bytes and KSOAP2

    Hello
    I have a request. I have a MSSQL database into two columns. One is a varchar and the second is the Image type. I would use these two fields filled to KSOAP2. I tried to send a picture in KSOAP byte array but it did not, probably, I sometimes confuse.
    Here is the source code.

    public byte[] getBytesFromBitmap(Bitmap bmp) {
     try {
      int height=bmp.getHeight();
      int width=bmp.getWidth();
      int[] rgbdata = new int[width*height];
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      DataOutputStream dos = new DataOutputStream(bos);
      bmp.getARGB(rgbdata,0,width,0,0,width,height);
      for (int i = 0; i < rgbdata.length ; i++) {
       if (rgbdata[i] != -1) {
        dos.writeInt(i);
        dos.flush();
        //l++;
       }
      }
      bos.flush();
      return bos.toByteArray();
     } catch (Exception ex) {
      Dialog.alert("getBytesFromBitmap: " + ex.toString()); return null;
     }
    }
    
    Bitmap borderBitmap = Bitmap.getBitmapResource("rounded.png");
    byte[] img = getBytesFromBitmap(borderBitmap);
    String name = "Name";
    SoapObject rpc = new SoapObject(serviceNamespace, "name");
    
    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
    rpc.addProperty("_img", img);
    rpc.addProperty("_string", name);
    envelope.setOutputSoapObject(rpc);
    envelope.bodyOut = rpc;
    envelope.dotNet = true;
    envelope.encodingStyle = SoapSerializationEnvelope.XSD;
    

    I also tried... I transferred the image in the array of bytes to a string, using the string, I sent KSOAP and everything went well... The problem was that if she string converted to array of bytes, and then in a Bitmap, then bb do not show Bitmap. I would like to send a byte array.

    Thank you

    Stepan

    This function is useful to get the bytes of the image.

    public static byte[] returnByte(String path)
    {
    FileConnection fconn;
    int available = 0;
    InputStream input = null;
    byte[] data=null;
    try
    {
    fconn = (FileConnection)Connector.open(path);
    if(fconn.exists()==true)
    {
    input = fconn.openInputStream();
    available = input.available();
    int fSz = (int)fconn.fileSize();
    data = new byte[fSz];
    input.read(data, 0, fSz);
    }
    }
    catch(Exception e)
    {
    Dialog.alert("Error");
    }
    return data;
    }
    

    Now you must do this:

    Byte [] img = returnByte ("pawan.png");

    rpc.addProperty("_img", Base64.encode(img));
    

    I'm sure it works...

    Thank you

  • array of byte size limit]

    I download & save multimedia files (video/pdf) using following code. The question is his works well for small size files MB (1 MB to 18 mb), but for some 60 MB files it stuck during the download. or sometimes download does not start. Thr is a size limit for byte array coz I am booting with the length of the file. This len contains the bytes to be read

    int

    Len = (int) hc.getLength ();

    byte data = newbyte[len];

    if (len > 0) {

    intactual = 0;

    intBytesRead = 0;

    while ((bytesread! = len) & (real! = - 1)) {

    real =

    tell. Read (data, bytesread, len - bytesread);

    bytesRead += real;

    percentage = bytesread * 100;

    percentage = percentage / len;

    int p = percentage (int);

    ProgressIndicatorScreen.

    this.model.setValue (p);

    }

    }

    I don't think that there is a size limit for an array of bytes, this is probably a problem with the connection. Download large files has been difficult for ever.

  • Pass an array of bytes to the oracle stored procedure

    I have a problem with moving from byte array in Oracle stored procedure as an input parameter by using odp.net.

    Here is the signature of the stored procedure:

    SOMEPROCEDURE(session IN NUMBER, data IN RAW)

    Here is c# code, which calls the procedure:

    var cmd = new OracleCommand("SOME_PROCEDURE", _connection);

    cmd.CommandType = CommandType.StoredProcedure;

    var bt = new byte[]{1,68,0,83,128,1};

    OracleParameter sessionId = new OracleParameter("dbSessionId", OracleDbType.Decimal, new OracleDecimal(_dbSessionId), ParameterDirection.Input);

    OracleParameter data = new OracleParameter("statusData", OracleDbType.Raw, new OracleBinary(bt), ParameterDirection.Input);

    cmd.Parameters.Add(sessionId);

    cmd.Parameters.Add(data);

    cmd.ExecuteNonQuery();

    This code does not (stored procedure throws exception, which cannot receive), because in byte array hadou number 128!, if I display 128 on another number, minus 128, it works great!

    What should I do?

    After some tests I found the solution. Initially, you cannot switch to the array of bytes via the odp.net stored procedure, if the table contains 127 large values.

    Yes, solution: 1. create the wrapper procedure

    procedure SOME_PROCEDURE_WRAPPER (p_session_id in number, p_data  in varchar2)
     is v_data raw(1024);
     rawdata raw(1024); 
     rawlen number;
     hex varchar2(32760);
     i number;
     begin
      rawlen := length(p_data);
      i := 1;
      while i <= rawlen-1
      loop 
     hex := substrb(p_data,i,2); 
         rawdata := rawdata || HEXTORAW(hex); 
         i := i + 2; end loop; 
         SOME_PROCEDURE(p_session_id , rawdata); 
     end;
    

    2 then need to modify the code c# in this way:

     var cmd = new OracleCommand("SOME_PROCEDURE_WRAPPER", _connection);
     cmd.CommandType = CommandType.StoredProcedure;
     string @string = statusData.ToHexString();
     OracleParameter sessionId = new OracleParameter("dbSessionId", OracleDbType.Decimal, new OracleDecimal(_dbSessionId), ParameterDirection.Input);
     OracleParameter data = new OracleParameter("statusData", OracleDbType.Varchar2,@string.Length, new OracleString(@string), ParameterDirection.Input);
     cmd.Parameters.Add(sessionId);
     cmd.Parameters.Add(data);
     cmd.ExecuteNonQuery();
    

    where

    public static string ToHexString(this byte[] bytes)
     { 
         if(bytes == null || bytes.Length == null)
               return string.Empty;
          StringBuilder hexStringBuilder = new StringBuilder();
          foreach (byte @byte in bytes)
          { 
              hexStringBuilder.Append(@byte.ToString("X2")); 
          } 
          return hexStringBuilder.ToString();
     }
    
  • Sending the command apdu with an array of bytes as CDATA

    Hello
    I learn the java card as part of my final year project. So far I think I can do the most basic things, but I stuck a special moment.

    I know that there are different manufacturers to create an apdu command object and a number of these manufacturers take an array of bytes as CDATA values.

    My problem is, how do I access this data table in the side of the card because apdu.getBuffer () returns an array of integers (bytes)? And what is actually on apdu.getBuffer () [ISO7816. (Instead of OFFSET_CDATA)] when you send the apdu command object using such constuctor?

    concerning

    Published by: 992194 on 6 March 2013 06:12

    992194 wrote:
    (..) I should have mentioned earlier that my card use jc 2.2.1 version, and from different places, I've read that this version does not support ExtendedLength facilities.

    Indeed.

    I also understand the semantics of apdu.getBuffer () [ISO7816. OFFSET_CDATA] is the first byte of the data command. My question is, these command data was initially provided as an array of bytes. Something like this:

    + new CommandAPDU(CLA, INS, P1, P2, DATA_ARRAY, Le) +.

    For example, when you call:

    ubyte [] buffer = apdu.getBuffer)

    So it means that the values of bytes inside the tableau_donnees argument automatically occupy locations + buffer [ISO7816. OFFSET_CDATA] + inside the buffer?

    Yes. The length would be (abstract) (buffer [ISO7816. (OFFSET_LC] & 0xFF) . Notice the & 0xFF is a must greater than 127 bytes.

    Or there is a mechanism to extract the table tableau_donnees itself?

    Laughing out loud

    In fact, in the interest of performance and portability in environments with low memory, usual coding style must pass buffer , an offset that and length; rather than take an object, which would require a copy. Welcome to the real world of Java Card.

  • How to convert an array of bytes in a single integer

    Hello!

    So, for the moment, I am trying to receive data from a device that sends data back as an array of 10 bytes, where the first 2 bytes are a header, 6 are a number of words that is supposed to be a unique 48-bit value and the last 2 are a number of errors which is suppose to be a unique 16-bit value.

    Ex:

    Word has received

    (Header)   (----------------------------------Word Count------------------------------)   (Number of errors)
    0            120     0               44              221          155          96             48             0              0

    So, in theory, what I want to do is be able to calculate the values like this:

    (Header)   (----------------------------------Word Count------------------------------)   (Number of errors)
    0            120     0               44              221          155          96             48             0              0
    The binary values: 00000000 00101100 11011101 10011011 01100000 00110000 00000000 00000000
    Concat. Vals: 000000000010110011011101100110110110000000110000 0000000000000000
    Calc'd Vals: = 192696508464 words = 0 errors
    * 40 (40-bit words)
    Totals: = 7.7078603e + 12 bits total = 0 Total errors

    But the problem that I am running is that all methods that I use seem to not be correct.

    I tried:

    Flatten the data and then it unflattening like a U64

    Convering to bool, concatinating tables data, and then convert that to a certain number

    Join all the bytes together using the join function

    Casting to an array of bytes to a U64

    And with all methods, the data that I use is incorrect (in the sense where the values are incorrect compared to this calculation manually like I did above), and at this point, I'm not sure how to get the correct values, so any kind of help would be greatly appreciated!

    Thank you!

    It seems to work for me...

  • Problem of cast to array of bytes in array of float

    Can someone help me find this process I am doing wrong?

    • I read a string of 6 tanks during the series.
    • I take the string and convert it to an array of bytes.
    • I then reverse the byte array because my microcontroller first sends the LSB and Labview is Big-endian
    • I catalogued this table in an array of float
    • I invert the table again to retrieve the data in the original order

    I can see the bytes in the array of bytes as 'byte, 0, 0, 0' when there are a small number, but when I I cataloged get very large or very small floats. Can someone help me understand this?

    Thank you!

    LabVIEW 2011

    You should probably use string unflatten, select the byte with rule of the little order and use a DBL 1 d array type. Everything must fall in place without all these gynastics bit, what you're doing.

    You can show us your code? I don't understand your use of "decimate the table."

    Attach a small VI containingh a typical chain received as a constant of diagram.

  • Array of bytes to double signs for AutoPowerSpectrum

    I'm trying to analyze a wav file and get the thd.

    During the read wav file, I read in one data (void *) table.  And according to the type of bit, depends on how to call PlotWaveform.  So, in my example, I have a 16-bit mono signal.  And I'm calling draw the waveform as follows:

    PlotWaveform (panelHandle, PANEL_CHANNEL_LEFT, channel1, samplesPerChannel, type, 1.0, 0.0, 0.0, 1.0, VAL_THIN_LINE, VAL_EMPTY_SQUARE, VAL_SOLID, 1,
                            VAL_RED);
    

    And a perfect sine wav out.

    Now, I try to do the THD on the signal, but can't convert my array of bytes in a double table.  I have the following code, but all my values that I use are in power - 319th.

    channel 1 is a (void *)

    I guess that the ConvertArrayType () function can help you in this problem.

  • Large array of bytes sent via socket?

    Hello

    I have had this problem for a while and have never really stood under how to solve it properly. I don't understand how you are supposed to transfer arrays of bytes that are larger than the size of the buffer of the socket. I have semi overcome them chapter by chapter from the table and write through the sleeve and reassemble frequently on the other side, but this causes problems. What is the right way to send a byte array that is larger than the buffer socket on an outputstream?

    I suspect that I am thick here, but I'm not aware that there is something called a socket buffer.  Actually, let me rephrase.  I'm not aware that there is a specific size that was a little to the amount of data to a socket can accept.

    And you should, in theory, be able to send constantly bytes on a socket and the IP protocol should ensure that they arrive in the right order, at the other end, providing the connection is maintained.

    In practice there are limits, but I wasn't aware of a buffer size of socket specific related to the shots of Blackberry (or any Sockets besides /).

    The original poster might explain what determines the size of this buffer?

  • Array of bytes in JSON string is not a valid JSONObject.

    I get an array of bytes from a URL that I can view in Google Chrome as a valid JSON object.

    When I get the answer to IOUtilities.streamToBytes (), it returns in the following way:

    [16, 8, 1, 10, 2,... 1, 0, 0, 8, 0, 0, 120, 2, 0]
    

    How can I convert the byte array to a human readable string I can spend in the JSONObject constructor?

    I tried the following character encodings:

    • "ISO-8859-1".
    • 'UTF-8 '.
    • "UTF-16BE".
    • "US-ASCII".

    Hello

    First, check with your http connection that it returns the appropriate response.

               connection=(HttpConnection)Connector.open(url,Connector.READ);
                connection.setRequestMethod(HttpConnection.GET);
                if(connection.getResponseCode()==HttpConnection.HTTP_OK)
                {
                    inputstream=connection.openInputStream();
                    int ch;
                    buffer=new StringBuffer();
                    while((ch=inputstream.read())!=-1)
                    {
                        buffer.append((char)ch);
                    }
                    System.out.println(buffer.toString());
                }
    

    If so, you need to spend just that data in json for parsing.i

    Thankx

  • Array of bytes to bitmap

    I'm trying to convert an array of bytes into a bitmap image.  The byte array returned from a url, if you enter the url in Internet Explorer, it is automatically returned.  What would be the best way to get the data returned by the url, and how would it be better to convert as bitmap?

    There is an example here:

    http://www.coderholic.com/BlackBerry-webbitmapfield/

  • Array of bytes Streaming playback

    Hello:

    Could someone french me some light, how could I impliment line three of the code in Labview?

    I have a pulse oximetry sensor conncected to Labview via a serial port VISA. Communication is very good, and I read 5 bytes successfully.

    However, each cycle, the context of the 3rd byte changes. Question is how can I build an array in the while loop (main), passing the value of octet 3 in another table.

    Byte0 | Octet1 | Octet2 | Byte 3 |  Byte4

    Number of sample to 1 / 1 255 255 100 255

    Number of sample2 1 255 255 255 50

    Number of Sample3 1 255 255 255 98

    The sensor will send 25 5bytes package, three times per second.

    The Streaming variable may represent 1 d table consists of 25 byte values #3.

    Then the rest of the algorithm would go on this Board on spidific, print the third value.

    For (i = 0; i<=25;>

    {

    InByte [i] = value ;} Streaming

    Serial.Print ("inByte [# favorite bytes print]" "");

    Could anyone recommend an appropriate approach rather tables? or it's the right path to take?

    I have attached the data of the page7 TCHF probe data sheet hanging in detail.

    Any help would be appreciated.

    KALOU

    Here is a similar example to what recommended Dennis.

    Lynn

  • Array of bytes to the Type specifier

    Hello everyone.

    In my project I have a connection to an external device via a RS-232 connection. Now, I read the bytes and want to convert them to a specified type, such as I32 or U8.

    When the data arrives, I convert the string to a byte array. For one serving, I need to convert an array of 4-byte an I32. This means that the bytes are literary the data to be converted to the data type.

    I have no idea how to do this, pourriez is it you guys please help me?

    Kind regards

    Jesse Bax

    Swissdrones of operations AG

    STH says:

    That's exactly what about built-in 'contact numbers.

    It's too much work.  Simply create a cluster of all data in the message and Unflatten string will do everything for you.

  • Suggestions of style of table binary array of bytes

    I have a specification that defines data message as a byte array, and each byte has specific bits that represent different things. So, I just set up an array of Boolean values that represent the bits of the message, then type cast to a selected table of u8 with convert 4.x. But the cast type function documentation says "Recommended of National Instruments reshuffle any application that uses the method of conversion data 4.x as a long-term solution." Is there a reason for this performance? I can think of other methods to remove the cast 4.x, but if I go another way, I would like to be able to justify why. Thank you.

    Something like that is probably what you're trying to do.

Maybe you are looking for