Byte[] to long

I'm writing an app that needs to deliver data to different places based on source and destination IP addresses. I was thinking that I could do this by stuffing the bits of both addresses into a long (source followed by destination) and then making a binary tree out of them.
Assuming I can get the addresses as byte arrays, would doing this:
long getAddresses(){
byte[] source=getSource();
byte[] dest=getDest();
long addresses= source[0]|source[1]|......source[7]|dest[0]|dest[1]|.....dest[7]; //pardon the paraphrasing
return addresses;
be the best way to go about things? I don't really care about the value of the longs, I only need to be able to compare them against each other and be sure that all pairs of addresses will produce a unique value, and as quickly as possible, since I need to handle lots of them.
Thanks for any advice.
Ewan

Well, if you don't really care obout the actual long values, a little byte-collecting
helper function will do:private long collect(byte[] b, long l) {
   for (int i= 0; i < b.length; i++) {
      l<<= 8;
      l|= b&0xffL;
return l;
Your getAddresses() might look like this then:long getAddresses(); {
   long l= collect(getSource(), 0);
   return collect(getDest(), l);
}kind regards,
Jos

Similar Messages

  • From byte to long

    Hi
    A very easy question. Imagine the byte 0xFF (Or 11111111). I want to build a long (64 bits length) having this byte on the last 8 bits starting from the right. That is:
    0000000....0000011111111
    If a write long l = (long) b, then l is -1 (Or 111111...11111). Is there any way to do this? Thanks in advance.

    byte b = (byte)0xff;
    long l = b;
    l &= 0xff;This solution works but this is not what I am looking
    for. Imagine that you do not know the value of the
    byte. This byte is only a variable. And the purpose
    is to set this byte at the end of the long bit
    String, that is, the first 8 bits starting from the
    right. Any ideas?That's exactly what the code does. You should only change the value of b.
    Kaj

  • Byte to long conversion.

    Hello.
    If you run this code, the result is "-13".
    Why this if "&oacute;" value is 243?
    Thanks.
    public class prueba3
    public static void main(String args[])
    byte[] b="&oacute;xxfd".getBytes();
    long b64=0;
    b64=(long)b[0];
    System.out.println(b64);
    }

    Hi elchaschab.
    Your method works, but needs a minimal of an Array of 8 bytes to work and consumes much processor in long process, like for example in array of 65555 bytes.
    I have proven the following code, but she does not convince to me because Java must to be able of a simple form to turn a byte to long without problems, no?
    public class prueba3
    public static void main(String args[])
    byte[] b="&oacute;xxfd".getBytes();
    long b64=0;
    for(int cont=0;cont<b.length;cont++) {
    b64=(long)b[cont];
    if(b64<0) b64=((b[cont]^254)*-1); // This line run ok, turns only the signed values to unsigned.
    System.out.println("b64("+((char)b[cont])+")="+b64);

  • Converting byte[] to short, long, etc.

    I need to packetize the data with my own header embedded in the data. The header field is composed of data types: short, byte, and long. Since the header will be transported over the network using UDP socket, it will have to be converted to type byte[].
    Is there a clean way to convert from byte[] to short, and long data types? Or do I have to concatenate bytes and type cast them? How do I even type cast byte[] to short? Thanks.

    Have a look at the ByteBuffer class. You can wrap a byte
    array in such a buffer and write other types (like ints or longs etc)
    to the byte array through the buffer. Of course you can read those
    values back again using the buffer.
    kind regards,
    Jos

  • Serial write takes unexpectedly long when more than 7 bytes are written

    Hi,
    My vi is attached. 
    As you see, it's very simple.
    - output buffer fifo is set to 128 bytes, which is generously higher than my needs.
    - my baudrate is 2.5 mpbs.
    - I write string of 9 bytes such as 012345678, and the execution time of the vi is around 40 us. 
      I thought it's because of the blocking structure of the synchronous write, and I decided to switch to asynchronous
      write, since I need to go above 20 kHz.
    - when I switch to asynchronous write, it even gets worse, and I get ~58 us. it seems like asynchronous doesn't work at all.
    so far, I explained my problem. I also did some simple experiments to debug the problem.
    - when my string is shorter than 8 bytes, everything is beautiful, asynchronous write takes nearly 15 us.
      when I enter an 8 bytes or longer string, it jumps up to 58 us again.
    what am I doing wrong? I'm stuck here.
    Gorkem Secer.
    Attachments:
    serialWrite_niForum_pic.png ‏19 KB

    The driver might for a lot of reasons not want to or even can't fill up the 8 byte hardware FIFO buffer entirely. This could be for instance since it has to work around some bugs in certain hardware. It might not be necessary for the specific hardware revision in your system but that driver has to work for many different hardware systems.
    The magnitude of timing control you try to achieve is simply beyond a software system if you require reliable and hard timings. It may be possible to achieve on a simpler but still powerful embedded system with custom made software drivers and RT OS but not on a more general purpose RT OS even if the hardware is pretty powerful. But such more custom made solutions would be more than a few magnitudes more expensive to develop.
    You can keep barking up this tree but it is unlikely that NI can do much about it without redesigning parts of the RT system, which is pretty much out of question as they simply license it from Ardence/IntervalZero and only adapt it where it is strictly necessary to work with their hardware. Most likely their license doesn't even allow them to customize it at will in any other way than is strictly necessary to get it to work on their own hardware.
    Your options are as far as I can see, to either rethink the timing requirements or adapt the software in such a way that the bigger delay won't be a problem or to go with a hardware solution based on an FPGA board or similar.
    As to the difference of asynchronous write and synchronous that is mostly about what VISA API is called underneath. The LabVIEW function remains blocking for as long as is necessary to pass the data to the OS driver. In synchonous mode the LABVIEW VI calls the synchronous VISA API once and that simply waits until VISA returns from the function. For the asynchronous case LabVIEW calls the asynchonous VISA function and then keeps looping inside its own cooperative multithreading layer until VISA indicates that the asynchonous function has been performed. This is mostly for historical reasons when LabVIEW didn't have OS supported multithreading and all the multithreading happened in the cooperative LabVIEW code scheduler. Nowadays asynchonous VISA mode has almost no benefits anymore but genearlly will cause significantly more CPU load.
    Rolf Kalbermatter
    CIT Engineering Netherlands
    a division of Test & Measurement Solutions

  • Read byte from a long

    Hi,
    How can I read bytes from a long. i..e read one byte by one byte from long.
    Naman Patel

    ok here is my problem how do i ignore the sign byte i.e please check this code
    long nr=1345345333L, add=7, nr2=0x12345671L;
              long tmp;
              long[] result = new long[2];
              char[] pwd = password.toCharArray();
              for (int pCount = 0; pCount < pwd.length; pCount++){
                   if (pwd[pCount] == ' ' || pwd[pCount] == '\t')
                        continue;
                   tmp= (long) pwd[pCount];
                   nr^= (((nr & 63)+add)*tmp)+ (nr << 8);
                   nr2+=(nr2 << 8) ^ nr;
                   add+=tmp;
              result[0]=nr & (((long) 1L << 31) -1L); /* Don't use sign bit (str2int) */;
              result[1]=nr2 & (((long) 1L << 31) -1L);
              int i = 0;
              long x = result[0];
              byte b[] = longToBytes(x);
              String str = "";
              i = 0;
              while(i < 4){
                   if(b[i] == 0x00) {
                        System.out.println("byte is 0x00");
                        str += "00";
                   else {
                        if(b[i] <= 0x0f && b[i] >= 0) {
                             System.out.println("byte is 0x0f" + b);
                             str += "0";
                        break;
                   i++;
              i = 0;
              str += Long.toHexString(result[0]);
              x = result[1];
              b = longToBytes(x);
              while(i < 4){
                   if(b[i] == 0x00) {
                        System.out.println("byte is 0x00");
                        str += "00";
                   else {
                        if(b[i] <= 0x0f && b[i] >= 0) {
                             System.out.println("byte is 0x0f");
                             str += "0";
                        break;
                   i++;
              str += Long.toHexString(result[1]);

  • P13n.ddl probs with UDB: field "value" too long to index

    We're trying to deploy the p13n.ddl on a UDB DB2 6.1.
    However, we encountered some problems:
    In UDB 6.1, an indexed column can be max 255 bytes long. So, the index
    WEBLOGIC_USER_ID_INDEX cannot be created, as the column "value" is one
    byte too long.
    CREATE TABLE WEBLOGIC_USER (userid int, property varchar(100), value
    varchar(256));
    CREATE INDEX WEBLOGIC_USER_ID_INDEX ON WEBLOGIC_USER (userid, property,
    value)
    How hard will omitting the "value" column from the index hit performance?
    All the columns in the table WEBLOGIC_USER has been indexed in one index.
    Was that done to prevent the DBMS from looking into the actual table at
    all (by looking only in the index)?
    Would it be possible to use the column as a varchar(255) or must it be
    256 chars wide? (Taking into consideration that the values at present are
    far from 256 chars.)
    Anders B. Jensen
    Consultant, Research & Development
    [email protected]
    LEC AS
    Denmark
    Remove the SPAMLESS to mail me.

    What you are trying to do shouldn't be a problem.
    There is no problems creating the weblogic_user as a varchar(255).
    I am not sure about omiting the "value" column and related performance
    issues, but I don't think it will be significant.
    "Anders B. Jensen" wrote:
    We're trying to deploy the p13n.ddl on a UDB DB2 6.1.
    However, we encountered some problems:
    In UDB 6.1, an indexed column can be max 255 bytes long. So, the index
    WEBLOGIC_USER_ID_INDEX cannot be created, as the column "value" is one
    byte too long.
    CREATE TABLE WEBLOGIC_USER (userid int, property varchar(100), value
    varchar(256));
    CREATE INDEX WEBLOGIC_USER_ID_INDEX ON WEBLOGIC_USER (userid, property,
    value)
    How hard will omitting the "value" column from the index hit performance?
    All the columns in the table WEBLOGIC_USER has been indexed in one index.
    Was that done to prevent the DBMS from looking into the actual table at
    all (by looking only in the index)?
    Would it be possible to use the column as a varchar(255) or must it be
    256 chars wide? (Taking into consideration that the values at present are
    far from 256 chars.)
    Anders B. Jensen
    Consultant, Research & Development
    [email protected]
    LEC AS
    Denmark
    Remove the SPAMLESS to mail me.

  • How to convert a integer into bytes!!!

    I am trying to pack the length of the data transamitted over a stream into 2 bytes (Each byte is a unsigned char in terms of 'C' language). When i am using the bytes in java any value greater than 127 is a negative number (I understand the very definition of 'byte' in java), my question is how to pack the length of the data the 'C' way still following Java rules??
    Example :: Length of the data is 168 say!
    the 2 bytes would be 0x00, 0x80 (the respective ascii values would be NULL, P) but with Java i get some thing different as we know??
    byte 1 = 00 and byte 2 = -88 ( i am not sure what would be the ascii equivalent of this??)
    Please help!

    For what it's worth:package ca.adaptor.util;
    * $Id: ByteUtil.java,v 1.6 2003/03/28 18:24:47 mike Exp $
    * Copyright (c) 2002 by Michael Coury
    *  This library is free software; you can redistribute it and/or
    *  modify it under the terms of the GNU Lesser General Public
    *  License as published by the Free Software Foundation; either
    *  version 2.1 of the License, or (at your option) any later version.
    *  This library is distributed in the hope that it will be useful,
    *  but WITHOUT ANY WARRANTY; without even the implied warranty of
    *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    *  Lesser General Public License for more details.
    *  You should have received a copy of the GNU Lesser General Public
    *  License along with this library; if not, write to the Free Software
    *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
    * @author Michael Coury (mdc)
    * @created Sep 20, 2002
    * @version $Revision: 1.6 $, $Date: 2003/03/28 18:24:47 $
    public final class ByteUtil {
      private static final int  __NUM_BYTES_IN_LONG_   = 8;
      private static final int  __NUM_BYTES_IN_INT_    = 4;
      private static final int  __NUM_BYTES_IN_SHORT_  = 2;
      private static final int  __NUM_BITS_IN_BYTE_    = 8;
      private static final long __BYTE_MASK_           = 0xFF;
      /** PRIVATE CONSTRUCTOR */
      private ByteUtil() {}
                ///// ENCODE /////
       * Converts a number to its binary equivalent and returns that as a byte array
      public static final byte[] toBytes(final long aNum) {
        final byte[] ret = new byte[__NUM_BYTES_IN_LONG_];
        for(int i = 0; i < __NUM_BYTES_IN_LONG_; i++)
          ret[i] = (byte) (aNum >>> ((__NUM_BYTES_IN_LONG_ - 1 - i) * __NUM_BITS_IN_BYTE_));
        return ret;
       * Converts a number to its binary equivalent and returns that as a byte array
      public static final byte[] toBytes(final int aNum) {
        final byte[] ret = new byte[__NUM_BYTES_IN_INT_];
        for(int i = 0; i < __NUM_BYTES_IN_INT_; i++)
          ret[i] = (byte) (aNum >>> ((__NUM_BYTES_IN_INT_ - 1 - i) * __NUM_BITS_IN_BYTE_));
        return ret;
       * Converts a number to its binary equivalent and returns that as a byte array
      public static final byte[] toBytes(final short aNum) {
        final byte[] ret = new byte[__NUM_BYTES_IN_SHORT_];
        for(int i = 0; i < __NUM_BYTES_IN_SHORT_; i++)
          ret[i] = (byte) (aNum >>> ((__NUM_BYTES_IN_SHORT_ - 1 - i) * __NUM_BITS_IN_BYTE_));
        return ret;
       * Converts a number to its binary equivalent and returns that as a byte array
      public static final byte[] toBytes(final double aNum) {
        return toBytes(Double.doubleToRawLongBits(aNum));
       * Converts a number to its binary equivalent and returns that as a byte array
      public static final byte[] toBytes(final float aNum) {
        return toBytes(Float.floatToRawIntBits(aNum));
                ///// DECODE /////
       * Converts a byte array representing a long back to a long
      public static final long toLong(final byte[] aNum) {
        try {
          long ret = 0L;
          for(int i = 0; i < __NUM_BYTES_IN_LONG_; i++) {
            ret += ((long) aNum[i] & __BYTE_MASK_) << ((__NUM_BYTES_IN_LONG_ - 1 - i) * __NUM_BITS_IN_BYTE_);
          return ret;
        catch(Exception e) {
          throw new NumberFormatException("Invalid number of bytes for long.  Found: " + aNum.length
                                          + " Required: " + __NUM_BYTES_IN_LONG_);
       * Converts a byte array representing an int back to an int
      public static final int toInt(final byte[] aNum) {
        try {
          int ret = 0;
          for(int i = 0; i < __NUM_BYTES_IN_INT_; i++)
            ret += (aNum[i] & __BYTE_MASK_) << ((__NUM_BYTES_IN_INT_ - 1 - i) * __NUM_BITS_IN_BYTE_);
          return ret;
        catch(Exception e) {
          throw new NumberFormatException("Invalid number of bytes for int.  Found: " + aNum.length
                                          + " Required: " + __NUM_BYTES_IN_INT_);
       * Converts a byte array representing a short back to a short
      public static final short toShort(final byte[] aNum) {
        try {
          short ret = 0;
          for(int i = 0; i < __NUM_BYTES_IN_SHORT_; i++)
            ret += (aNum[i] & __BYTE_MASK_) << ((__NUM_BYTES_IN_SHORT_ - 1 - i) * __NUM_BITS_IN_BYTE_);
          return ret;
        catch(Exception e) {
          throw new NumberFormatException("Invalid number of bytes for short.  Found: " + aNum.length
                                          + " Required: " + __NUM_BYTES_IN_SHORT_);
       * Converts a byte array representing a double back to a double
      public static final double toDouble(final byte[] aNum) {
        return Double.longBitsToDouble(toLong(aNum));
       * Converts a byte array representing a float back to a float
      public static final float toFloat(final byte[] aNum) {
        return Float.intBitsToFloat(toInt(aNum));
                ///// SHIFTING /////
      public static final byte shiftRightUnsigned(final byte b, final int shift) {
        return (shift > __NUM_BITS_IN_BYTE_) ? 0x00 : (byte) ((b & 0xFF) >>> shift);
      public static final byte shiftRight(final byte b, final int shift) {
        return (byte) (b >> shift);
      public static final byte shiftLeft(final byte b, final int shift) {
        return (shift > __NUM_BITS_IN_BYTE_) ? 0x00 : (byte) (b << shift);
    }

  • Jlong to long !

    Hi ;
    What casting should I do to jlong inorder to get a proper long representing the same number .
    running the next example gives the below resault :
    int main()
    jlong f = 40956436157 ;
    unsigned long g = (unsigned long)f ; // my jlongs will always be positive values
    cout <<"testing ="<<g<<endl;
    return 1 ;
    resault :
    testing =2301730493
    (I tried first with simple long casting and I got :      -1993236803 )
    I understand that the problem must be with the number of bits representing the long type in c++ , but are there any ideas ?
    Thanks ;
    Adaya .

    updates ...
    checking with the sizeof(type) method it realy seems that the problem is with the number of bytes that long and jlong are represented by ,
    while long is represented by 4 bytes (which is very odd-isnt it suppose to be 8?) jlong is represented by 8...
    is there anything to do about it ?
    Adaya .

  • Long data: Use of SQL_LEN_DATA_AT_EXEC(0) and SQL_DATA_AT_EXEC

    Hello,
    What is the use of SQL_LEN_DATA_AT_EXEC(0) and what does it mean ?
    I know that when StrLen_or_IndPtr buffer
    pointer of SQLBindParameter is set to SQL_LEN_DATA_AT_EXEC  or SQL_DATA_AT_EXEC
    it means that the data for the parameter will be sent with SQLPutData.  Also SQL_LEN_DATA_AT_EXEC(length)
    is used when sending long data to a data source that needs to know how many bytes of long data will be sent so that it can preallocate space
    But what should be the expected  behavior when we set StrLen_or_IndPtr buffer
    to:
         1)  SQL_LEN_DATA_AT_EXEC(0)
    or  2)  SQL_DATA_AT_EXEC
    Thanks
    Mukesh

    Hi Elvis,
    Thanks for reply!
    But my question is what should be the expected  behavior when we set StrLen_or_IndPtr buffer
    to:
         1)  SQL_LEN_DATA_AT_EXEC(0)
    or  2)  SQL_DATA_AT_EXEC
    I think it should insert all data using SQLPutaData limited by the length of columns size.
    MSDN is silent in the case of SQL_LEN_DATA_AT_EXEC(0)
    Thanks,
    Mukesh

  • Syncing BLOB results in 0 byte file

    Hello, I have a custom VB program that scans a driver's license. The face image and text are then saved to the OLite client DB. However, when I sync to the server, the BLOB field is 0 bytes in the target table.
    I have based the handling of the BLOB in my program on the BLOB sample code that is delivered with the Oracle Lite sample code <ora lite home>\mobile\sdk\samples\ado.net\win32\blob. When I run that code, it writes to the mobile client DB and then re-queries the BLOB, as it should. In order to test this with the sync, I then modified that sample code so that it writes the BLOB to my own table rather than the sample table. I then run msync, and it is also 0 bytes on the server. Is this some bug or maybe some setup that is missing? The code below is the section that handles the BLOB inserting and reading. I hope someone can help ... thanks in advance!
    ryan
    ++++++++++++++++++++++++++++++++++++++
    Private Sub Run()
    Dim conn As OracleConnection
    ' Create Database
    SetDone(lblCreate, False)
    ' Open database connection
    Dim dsn As String = "dsn=IDMAN32_" & "emready;uid=system;pwd=IDMAN32"
    conn = New Oracle.DataAccess.Lite.OracleConnection(dsn)
    conn.Open()
    SetDone(lblCreate, True)
    ' Create a table with a blob column
    Dim cmd As IDbCommand
    Dim blob As OracleBlob
    SetDone(lblTable, False)
    cmd = conn.CreateCommand()
    ' Create new BLOB object in polite database
    SetDone(lblInsert, False)
    blob = New OracleBlob(conn)
    'Read data from the image file and write it into the blob
    'in chunks
    Dim file As FileStream
    Dim browse As System.Windows.Forms.OpenFileDialog = New System.Windows.Forms.OpenFileDialog
    browse.Filter = "Bitmap (*.bmp)|*.bmp|Gif (*.gif)|*.gif"
    browse.Title = "Choose an Image File"
    browse.ShowDialog()
    Dim imageSrc As String = browse.FileName
    Dim imageDes As String = "tmp.gif"
    If imageSrc Is Nothing Or imageSrc.Length = 0 Then
    imageSrc = "oracle.gif"
    End If
    file = New FileStream(imageSrc, FileMode.Open, FileAccess.Read)
    Dim ImageData As Byte()
    ReDim ImageData(file.Length)
    Dim ArraySize As Integer = New Integer()
    ArraySize = System.Convert.ToInt32(file.Length)
    file.Read(ImageData, 0, ArraySize)
    file.Close()
    ' Insert our image blob into the table using LiteParameter
    cmd.CommandText = "insert into EMPLOYEE_STAGING (EMPLOYEE_ID, PHOTO) values(11000, ?)"
    cmd.Parameters.Add(New OracleParameter("Image", blob))
    cmd.ExecuteNonQuery()
    cmd.Parameters.Clear()
    conn.Commit() ' Commit transaction
    SetDone(lblInsert, True)
    ' Read blob from the Database and write to a temp file
    SetDone(lblRead, False)
    Dim reader As IDataReader
    cmd.CommandText = "select EMPLOYEE_ID, PHOTO from EMPLOYEE_STAGING WHERE EMPLOYEE_ID=11000"
    reader = cmd.ExecuteReader()
    If reader.Read() = False Then
    cmd.Dispose()
    conn.Close()
    Throw New Exception("Failed to read blob")
    End If
    blob = reader.GetValue(1)
    reader.Close()
    file = New FileStream(imageDes, FileMode.Create, FileAccess.Write)
    file.Write(ImageData, 0, ArraySize)
    file.Close()
    ' Close database connection
    conn.Close()
    SetDone(lblRead, True)
    ' Display bitmap
    Dim bmp As Bitmap
    bmp = New Bitmap(imageDes)
    bmpBox.Image = bmp
    End Sub

    Oracle just posted a sample today as well.
    Caution
    This sample code is provided for educational purposes only and not supported by Oracle Support Services. It has been tested internally, however, and works as documented. We do not guarantee that it will work for you, so be sure to test it in your environment before relying on it.
    Proofread this sample code before using it! Due to the differences in the way text editors, e-mail packages and operating systems handle text formatting (spaces, tabs and carriage returns), this sample code may not be in an executable state when you first receive it. Check over the sample code to ensure that errors of this type are corrected.
    Sample Code
    Create the Oracle Lite Database
    1. Create a new folder c:\ClobTest.
    2. Open a Command Prompt.
    3. Issue the command CREATEDB ClobTest c:\ClobTest\ClobTest.odb test.
    4. Exit the command prompt.
    Create the ODBC Data Source Name
    1. Open the ODBC Data Source Administrator.
    Start, run, odbcad32.exe.
    2. Under either User DSN or System DSN, click Add.
    3. Select Oracle Lite 40 ODBC Driver and click Finish.
    4. Enter the following configuration information:
    Data Source Name: ClobTest
    Data Description: Clob Test Database
    Database Directory: C:\ClobTest
    Database: ClobTest
    Default Isolation Level: Read Committed
    Autocommit: Off
    Default Cursor Type: Forward Only
    5. Click OK and close the ODBC Data Source Administrator.
    Create Oracle Database Lite Table
    1. Open a Command Prompt.
    2. Connect to the ClobTest Database with mSQL.
    msql system/Test@jdbc:polite:ClobTest.
    3. Create the TEST_CLOB table.
    create table TEST_CLOB(
    field1 VARCHAR2(60) PRIMARY KEY,
    text CLOB);
    commit;
    4. Exit msql and exit the Command Prompt.
    Create the Visual Studio 2005 C# ClobTest Project
    1. Launch Visual Studio 2005.
    2. Select Create Project.
    3. Select the Visual C# Language and Windows for the project type, select the Windows Application template, name the project ClobTest, and click OK.
    Reference the Oracle Database Lite ADO.Net 2.0 provider
    1. Select Project, Add Reference.
    2. Select the Browse tab.
    3. Navigate to the <Olite SDK Home>\Mobile\Sdk\ado.net\v2.x direcotry.
    4. Highlight Oracle.DataAccess.Lite_w32.dll file and click OK.
    Create the ADO.Net ClobTest Application
    1. Add the following class declarations to the declarations already contained by default:
    using System.IO;
    using Oracle.DataAccess.Lite;
    using Oracle.Lite.Data;
    using System.Diagnostics;
    2. Declare a LiteConnection object in class scope.
    LiteConnection con;
    3. Instantiate the connection object in the Form_Load method.
    con = new LiteConnection("DataDirectory=C:\\ClobTest;Database=ClobTest;DSN=*;uid=system;pwd=test");
    4. Create a button object named cmdInsert wtih a text property of Insert.
    5. Add the following code to the cmdInsert_Click method:
    LiteCommand cmd = new LiteCommand(con);
    byte[] buffer = new byte[5];
    long lngOffset = 0;
    try
    con.Open();
    Debug.Print("Connection Open");
    LiteLob clobText = new LiteLob(con);
    buffer = Encoding.UTF8.GetBytes("Smile");
    //Clob Max = 2000000000 so with 5 max setting should be 400000000)
    while(lngOffset < 400)
    clobText.SetBytes(lngOffset, buffer, 0, 5);
    lngOffset += 5;
    cmd.CommandText = "INSERT INTO TEST_CLOB VALUES('Record 1', ?)";
    cmd.Parameters.Add(new LiteParameter("text", clobText));
    cmd.ExecuteNonQuery();
    cmd.Parameters.Clear();
    con.Commit();
    MessageBox.Show("Clob Successfully Inserted", "Done");
    catch (Exception ex)
    Debug.Print(ex.Message);
    finally
    if (con.Connection.State == ConnectionState.Open)
    con.Close();
    Debug.Print("Connection Closed");
    6. Create a button object named cmdRetrieve wtih a text property of Retrieve.
    7. Add the following code to the cmdRetrieve_Click method:
    LiteCommand cmd = new LiteCommand(con);
    IDataReader dr;
    FileStream file;
    byte[] buffer = new byte[256];
    long lngOffset = 0;
    long chunk;
    try
    con.Open();
    Debug.Print("Connection Open");
    cmd.CommandText = "SELECT * FROM TEST_CLOB WHERE FIELD1 = 'Record 1'";
    dr = cmd.ExecuteReader();
    dr.Read();
    LiteLob clobText = new LiteLob(con);
    clobText = (LiteLob)dr["TEXT"];
    file = new FileStream("c:\\ClobTest\\Retrieve.txt", FileMode.Create);
    Debug.Print("Text File Created");
    do
    chunk = clobText.GetBytes(lngOffset, buffer, 0, 256);
    file.Write(buffer, 0, (int)chunk);
    lngOffset += chunk;
    while (chunk != 0);
    file.Close();
    Debug.Print("Text File Closed");
    MessageBox.Show("Clob Successfully Retrieved", "Done");
    catch (Exception ex)
    Debug.Print(ex.Message);
    finally
    if (con.Connection.State == ConnectionState.Open)
    con.Close();
    Debug.Print("Connection Closed");
    Compile and test the sample
    1. Select the Debug menu and choose Start Debugging.
    2. Click on the Insert button to insert Clob data into the Oracle Lite database. The size of the Clob data may be altered by changing the while loop while(lngOffset < 400) to use a larger value.
    3. Click on the Retrieve button to retrieve the Clob data from the database and write it as a new file.
    4. Verify that the Retrieve.txt file is created in the c:\ClobTest folder and that the text may be viewed
    correctly.

  • Getting the base-36 representation of a byte[8]

    Hello all.
    I am in the process of writing a J2ME client for a properitary protocol transmitting stock data.
    Simply put my problem is that I need to get the base-36 (0-9AZ) representation of a 64 bit unsigned number (stored in a byte[8]).
    To be more elaborate, I am encrypting a string using the Blowfish algorithm (from www.bouncycastle.org), and the resulting blocks are to be sent to the server as a base36 string representing the block.
    Since I am on J2ME I do not have access to Sun's BigInteger, but Bouncycastle provides a lightweight one, however I think it is a bit buggy. Nor do I have access to the J2SE formatter classes.
    Ideally I would want to do something like this:
    Long.toString( (long)bytearray, 36 );
    This of course do not work since
    1) Jave does not support casting byte[] to long, this could however be fixed by bitshifting.
    2) Long is always signed and I am really at a loss on how to do this.
    Any ideas?
    Regards Johan Seland

    Is your byte array big endian or little endian? I'll assume little endian.
    package base36;
    import java.util.*;
    * <p>Single Sentence Description. </p>
    * <p>Long Description. </p>
    * <p>Copyright: &copy; 2003</p>
    * <p> </p>
    * @author Paul Murray
    * @version 1.0
    public class Main
        public static void main(String[] args) {
            Main main1 = new Main();
            main1.go();
        void go() {
            for (int i = 0; i < 13; i++) {
                System.out.print("36 ^ " + i + " = ");
                for (int j = 0; j < 8; j++) {
                    System.out.print(Integer.toHexString((((int)powers[i][j])>>4)&15));
                    System.out.print(Integer.toHexString(((int)powers[i][j])&15));
                    System.out.print(' ');
                System.out.println(' ');
            byte[] amt;
            amt = new byte[] {0, 0, 0, 0, 0, 0, 0, 0};
            dump(amt); System.out.println(" = " + cvt(amt));
            amt = new byte[] {1, 0, 0, 0, 0, 0, 0, 0};
            dump(amt); System.out.println(" = " + cvt(amt));
            amt = new byte[] {0, 1, 0, 0, 0, 0, 0, 0};
            dump(amt); System.out.println(" = " + cvt(amt));
            amt = new byte[] { -1, -1, 0, 0, 0, 0, 0, 0};
            dump(amt); System.out.println(" = " + cvt(amt));
            amt = new byte[] { 0, 0, 1, 0, 0, 0, 0, 0};
            dump(amt); System.out.println(" = " + cvt(amt));
            amt = new byte[] { -1, -1, -1, -1, -1, -1, -1, -1};
            dump(amt); System.out.println(" = " + cvt(amt));
            amt = new byte[] { -2, -1, -1, -1, -1, -1, -1, -1};
            dump(amt); System.out.println(" = " + cvt(amt));
        void dump(byte[] d) {
            for(int i=0;i<8;i++) {
                System.out.print(Integer.toHexString((((int)d)>>4)&15));
    System.out.print(Integer.toHexString(((int)d[i])&15));
    System.out.print(' ');
    * powers of 36. we use an array of short to nix sign extension. I happen to know that
    * there are 13 powers of 36: n < 2^64
    static short[][] powers = new short[13][];
    static {
    // initialise the array of powers of 36
    short[] p = new short[] {
    1, 0, 0, 0, 0, 0, 0, 0};
    int index = 0;
    for (; ; ) {
    powers[index] = new short[8];
    System.arraycopy(p, 0, powers[index], 0, 8);
    index++;
    int carry = 0;
    for (int i = 0; i < 8; i++) {
    int mul = p[i] * 36 + carry;
    p[i] = (short) (mul & 0xFF);
    carry = mul >> 8;
    if (carry != 0)
    break;
    assert index == 13:"there are exactly 13 64-bit powers of 36";
    // use a single instance - not thread safe
    short working[] = new short[8];
    StringBuffer amt = new StringBuffer();
    String cvt(byte[] n) {
    if (n.length != 8)
    throw new IllegalArgumentException("length of 8, please");
    amt.setLength(0);
    for (int i = 0; i < 8; i++)
    working[i] = (short) ( ( (int) n[i]) & 0xFF);
    for (int currentPower = 12; currentPower >= 0; currentPower--) {
    int digit = 0;
    while (lessThanOrEqualToWorking(powers[currentPower])) {
    digit++;
    subtractFromWorking(powers[currentPower]);
    if (digit < 10) {
    amt.append((char)('0' + digit));
    else {
    amt.append((char)('A' + digit - 10));
    return amt.toString();
    boolean lessThanOrEqualToWorking(short[] p) {
    assert p.length == 8;
    for (int i = 7; i >= 0; i--) {
    if (p[i] > working[i])
    return false;
    if (p[i] < working[i])
    return true;
    return true;
    void subtractFromWorking(short[] p) {
    assert p.length == 8;
    boolean carry = false;
    for (int i = 0; i < 8; i++) {
    if (carry)
    working[i]--;
    working[i] -= p[i];
    if (working[i] < 0) {
    working[i] += 256;
    carry = true;
    else {
    carry = false;
    assert!carry:"param must be < working";

  • UUID to byte[]

    Hello,
    I don't understand how to convert a UUID object into a byte sequence (of same format as UUID.nameUUIDFromBytes(byte[]) takes in parameter)
    I've coded i little method but it doesn't give me a correct byte array, i've tested the output with UUID.nameUUIDFromBytes(byte[]) and it doesn't return the original key.
    protected byte[] encode(UUID key){
            ByteBuffer keyBuffer = ByteBuffer.allocate(16);
            keyBuffer.order(ByteOrder.BIG_ENDIAN);
            keyBuffer.putLong(key.getMostSignificantBits());
            keyBuffer.putLong(key.getLeastSignificantBits());
            return keyBuffer.array();
    }Example :
    public static void main(String args[]){
            UUID before = UUID.fromString("a53e607c-e9c7-475f-a938-9ae6331d85b1");
            byte b_uuid[] = encode(before);
            UUID after = UUID.nameUUIDFromBytes(b_uuid);
            System.out.println(before.toString()+" - > "+after.toString());
    }Output : a53e607c-e9c7-475f-a938-9ae6331d85b1 - > 625c894f-dfa5-3b8e-b577-458d7d676fe0
    Any idea ?

    writing:
    long hibits = id.getMostSignificantBits();
    long lobits = id.getLeastSignificantBits();
    // A. then just write the two longs...
    // B. or if you really want byte[]s...
    byte[] hibytes = new BigDecimal(hibits).toByteArray();
    byte[] lobytes = new BigDecimal(lobits).toByteArray();reading:
    // (B.) decode the byte[] to longs
    long hibits = new BigInteger(hibytes).longValue();
    long lobits = new BigInteger(lobytes).longValue();
    // (A.) read two longs from your stream
    id = new UUID(hibits, lobits);

  • Bytes per Second

    Dear Reader,
    I have made my simple download utility program in java.
    In there i can count the number of bytes downloaded.
    --Problem i am facing is to get bytes per second of the download in progress.
    For this purpose i take system time at definite intervals(one or two seconds) and count
    the bytes downloaded in that specific intervals.
    Doing so slows down the speed of the program(execution speed).
    If you have any alternative to get bytes per second which does not consume time please
    notify...
    Thank you

    Make sure you don't have a lot of System.out.prints when you calculate the speed, and instead of reading just one byte at the time, you could read x bytes at the time using a byte array.
    byte[] buffer = new byte[1024];
    long start = System.currentTimeMillis();
    long bytesRead = 0;
    int len;
    while (System.currentTimeMillis()-start < 2000 && (len = in.read(buffer)) != -1) {
      bytesRead += len;
      // ... do something with the read bytes.
      // Valid bytes are in the buffer from index 0 to len-1, the rest is garbage
    long rate = 1000*bytesRead/(System.currentTimeMillis()-start);
    System.out.println("Current rate is: "+rate);Something like that..

  • Restore from Time Capsule after Hard Drive Crash

    The HD on my iMac crashed Christmas Day. I have been running backups on Time Machine to a Time Capsule since I purchased the iMac (and also backing up a MacBook Air), but never had any occasion to see if it worked.
    I yesterday got the computer back with a new HD installed. When I tried to do the restore from Time Capsule from the Setup Assistant which ran on start up, I could not get past the initial screen. It kept hanging up on "Opening Time Capsule," and then on one occasion it found only the MacBook Air back up volume.
    After some research here, I tried running the utility after booting from my Snow Leopard disk. This time, it immediately found the backups from both computers, but hung up on opening the iMac backup.
    After more research, I ran the disk utility and repaired the HD on the iMac. It finally worked -- I woke up to a "Restore Complete" message (it started around 10:00 pm last night). The iMac started up without a hitch to the way it looked Christmas morning. The only problem I have noticed is that my most recent events in iPhoto are empty. The thumbnails are there, but no pictures. I tried to rebuild the library using iPhoto Library Manager, but no luck. Any ideas?
    The other thing I noticed is that I had to reauthorize the computer for my iTunes purchases. Will Apple fix that so it doesn't chew up my last remaining authorization?

    think about the speed of wifi here
    speed at 802.11n = a theoretical 540Mbps (less in real world scenarios)
    Mbps = Mega bits per second
    MBps - Mega bytes per second
    8 bits = 1 byte
    8 mega bits = 1 mega byte
    How long would it take you to download a 1 gig file from the internet wired into your modem? About 10-20 min? And that is taking into account that the info is being uploaded hardwire. Now imagine that same file over wireless in your home being upload by the Airport card in your computer. People over look upload speed when considering these things. The wireless upload speed of your Airport card is what is limiting this. Just a limitation of the technology, not a fault of Apple just stating the numbers here.

Maybe you are looking for

  • Buying a hard drive

    I'm looking into buying a new [external] hard drive and I don't know what to look for aside from the capacity. I hope you guys can answer my questions below... - IDE or SATA? What's the difference and what should I get? - 8MB or 16MB? Obviously 16 is

  • My account has been cancelled

    Last night I received an email telling me I had placed an order to cancel my line and broadband. I never made this order, especially after having to wait TWO months to have my home move order activated.  I have called to cancel this order this mornin

  • Basic Help needed with Hyperion 9.3 Scheduling jobs

    Hi! Is there anyone who would be willing to help a novice understand the Scheduling features in Hyperion 9.3? We are converting from Brio 6.6 where we used the "Broadcast Server". We don't yet have many jobs - so I'm not migrating them. But, the docu

  • Date format used in the datepicker

    Hi, I have a problem with date format when I open the pop up calendar: w=open("wwv_flow_utilities.show_as_popup_calendar" +..... "&p_date_format=" + escape('MM/DD/YYYY HH:MI ' )... I have the popUp window with message instead of calendar: " NOT FOUND

  • Motion and Typography

    I am making a little kinetic typography project and am stuck. I am trying to make it so I zoom in on the dot of an i, so the dot of the i creates a new scene, but Motion doesn't seem to be able to that, or I am doing it incorrectly. First I just trie