Unsigned integer problem

Hi,
I have a problem of converting a CRand32 function from C to Java which was originally from IDA decompiler.
There's one thing that's troubling me for quite a long time which is the lack of unsigned types, I could not do operations such as byte shifting correctly and the end result I get is sometimes a negative number or larger than 4billion.
This CRand function should only generate 0 ~ 4billion.
Can anyone enlighten me in this? As it's the first time I am doing such things.
Here's the code I have from direct translation from C to Java :
    private transient long seed1, seed2, seed3; // In the code this is an unsigned int_32
    public final long CRand32__Random() {
     // assume the seed is already an unsigned long..
     seed1 = ((seed1 & 0xFFFFFFFE) << 12) ^
          (((seed1 << 13) ^ seed1) >> 19);
     seed2 = ((seed2 & 0xFFFFFFF8) << 4) ^
          (((seed2 << 2) ^ seed2) >> 25);
     seed3 = ((seed3 & 0xFFFFFFF0) << 17) ^
          (((seed3 << 3) ^ seed3) >> 11);
     return (seed1 ^ seed2 ^ seed3);
    }Thanks,
Edited by: LightPepsi on May 30, 2010 11:40 PM
Edited by: LightPepsi on May 30, 2010 11:40 PM

LightPepsi wrote:
That was the first thing which comes to my mind by changing >> to >>>, however the numbers generated are usually not within the range of an unsigned integer.
It can be sometimes a negative number or larger than 4 billion and thus making the randomizer inaccurate.One possibility is to use ints for the internal shifts, but create a long as
long unsignedValue = intValue & 0xFFFFFFFFL;for returning the number and possibly for any internal comparisons you need to make.
Winston

Similar Messages

  • Php Pack/unpack unsigned integer equivalent

    I'm trying to port some PHP code into Java which contains calls to Pack and Unpack which I'm trying to use which I'm having some problems with converting.
    I realise Java doesn't have these functions but I've been fiddling around and looking around the net trying to get a solution. The php is using 'I' as its format mask which is Unsigned Integer so I've used :
    Integer.toBinaryString(toStringInt)
    which should be returning the unsigned integer but I'm having trouble trying to get it back from the binary string.
    When I stick the result of the above code into Integer.parseInt(string, int) it gives me a number format exception
    Can anyone help?
    Thanks

    ok but how do I set the lower 32 bits? And what is setting the highest bit even doing because I have no idea how the server will respond if I don't set it. As I said I'm porting this from PHP which does all of this and doesn't explain why so I don't know what it's doing it for. The PHP is
    function _encodeHeader($isFromServer, $isResonse, $sequence)
         $header = $sequence & 0x3fffffff;
         if($isFromServer)
         $header += 0x80000000;
         if($isResponse)
              $header += 0x40000000;
         return pack('I', $header);
    That is what I'm porting from so that is why I'm setting the highest bit.

  • Modbus real to unsigned integer conversion

    Is there any alternative way of decoding the two unsigned integer 16 bit words received through Modbus when using reals? I am using the join numbers and type cast functions; however I am not able to download the complete Modbus list to a compact RIO with 32 MB RAM as it runs out of memory.

    Khalid,
    Thanks for your response. However, let me tell you more about my problem:
    Basically my project consists of:
    1. A list of shared variables within a library that also contains modbus slave with the communication settings.
    2. (5) VIs that used to convert UInt16 to Single (for inputs) and Single to UInt16 (for otputs)
    3. (1) VI to display information
    As I try to download into a cRIO-9002 with 32MB of RAM, the device drops the communication and goes into safe mode, blinking the STATUS light 4 times, this means "run out of memory" .
    I would like to know if there is any other alternative way to overcome this problem. Join and cast is functionally correct but it uses too much RAM

  • How to return array of unsigned integer pointer from call library function node & store the data in array in labview

    I want to return array of unsigned integer from call library node.
    If anybody knows please help me
    Thanks & Regards,
    Harish. G.

    Did you take a look at the example that ships with LabVIEW that shows how to do all sorts of data passing to DLLs. I believe your situation is one of the examples listed. You can find the example VI in the "<LabVIEW install directory>\examples\dll\data passing" directory.

  • Convert 8 bit unsigned integer to binary (base 2)

    i am trying to convert an 8 bit unsigned integer to binary (base 2) representation and use 8 LED's to show this representation.
    Like for integer 10, the binary is 00001010.....so the LED' s 1 and 3 should be on...

    The LED (boolean) indicators are simply placed into an array.
    To "borrow" an example of such a display, you could have a look at the code written for the parallel port example that can be found under the Help menu:
    Help > Find Examples :  Search "parallel"  HAve a look at the 1st or 2nd example.  They have LED's wired to a U8 array  (I think..  It's been a while since I looked at the example...   )

  • Unsigned integer

    Hello,
    I am trying to wrap a c++ dll ,where most of the variables are (unit8,unit16,uni32 ) unsigned integers.
    Since java doesnt have usigned integer type,I am wondering what to do.
    1. Pass the usigned int value as a string to the c++ program.Convert from string to uint in the C++ code.
    would be one option.
    I am hoping that there are other options available to do this more gracefully.
    thank you very much,
    Regards

    I agree that signed and unsigned numbers differ in interpretation of the bits so one can disregard this when passing the data to/from DLL.
    When you get an uint32 from the DLL it can be stored in a Java int type:
    int i=fromDLL();but it should be converted to long when used:
    long ui=(long)i&0xffffffff;to pass "unsigned" to the DLL convert it to int:
    toDll((int)ui);You may also need to perform little/big-endian conversion.
    Dmitry Hudyakov
    Brainbench MVP

  • Unsigned int - problem translating c++ function to java

    OK so here's the deal:
    I'm writing a client for a internet comunicator in java (J2ME to be precise). Unfortunately i have specs for this comunicator's protocol for c++ programing. The first problem I ran to is: I have to calculate a hash for a password so it doesn't go plain text on the network. The function in c++ that does this is:
    int getPasswordHash(char *password, int seed){
        unsigned int x=0, y=0, z=0;
        char *pwd = password;
        y = seed;
        for (x = 0; *password; password++) {
         x = (x & 0xffffff00) | *password;
         y ^= x;
         y += x;
         x <<= 8;
         y ^= x;
         x <<= 8;
         y -= x;
         x <<= 8;
         y ^= x;
         z = y & 0x1f;
         y = (y << z) | (y >> (32 - z));
        cout << "Hash for \"" << pwd << "\" with seed \"" << seed << "\": " << y << "\n";
        return y;
    }My translation to java goes:
    public int getPasswordHash(String password, int seed){
        long x = 0, y = 0, z = 0;
        int tmp = 0;
        String pwd = password;
        y = seed;
        for (x = 0; x < password.length(); x++){
            tmp = (int)x;
            x = x | password.charAt(tmp);
            y ^= x;
            y = uintadd(y, x);
            x <<= 8;
            y ^= x;
            x <<= 8;
            y = uintsubst(y, x);
            x <<= 8;
            y ^= x;
            z = y & 0x1f;
            y = (y << z) | (y >> (32 - z));
            x = tmp;
        System.out.println("Hash for \""+ pwd + "\" with seed \"" + seed + "\": " + y);
        return (int)y;
    public long uintadd (long x, long y){
        long xL = x & 0xffffffffL;
        long yL = y & 0xffffffffL;
        long sumL = xL + yL;
        long sum = (sumL & 0xffffffffL);
        return sum;
    public long uintsubst (long x, long y){
        long xL = x & 0xffffffffL;
        long yL = y & 0xffffffffL;
        long sumL = xL - yL;
        long sum = (sumL & 0xffffffffL);
        return sum;
    }So I use the uintadd and uintsubst to add and substract values that should be unsigned int. Every operation works exactly like in c++ (I've checked) until this point:y = (y << z) | (y >> (32 - z));and to be exact (y << z) This doesn't turn out like in c++ so the whole function doesn't return the right vaule. I know it's because doing a bit operation on a unsigned int in c++ is different in than in java because unsigned variables have totally different bit values than signed ones. The question is: how to work this out. I managed to do aritmetic operations working but I have no idea how to deal with this. Any help would be great.

    I'm by no means the expert with this, but I'm going
    to guess that this would work...
    y = ((y << z) & 0xffffffffL) | (y >> (32 - z));
    thus... to zero out the right shifted 1's before the
    orWOW WOW WOW it totaly works thanks alot bsampieri !!

  • Unsigned char[] problem

    hi,
    I am using JNI to test a C++ method that generates a random 128-byte unsigned char []. In my code, I've used a char[] to pass the unsigned char[] (as it always gives a positive number) and returned it as a jstring in Java.
    However, I'm not sure in Java how I can catch the unsighed bytes using the String returned. I tried using int[] and float[] but somehow I still get negative bytes.
    Could anyone pls give me some hints? any help would be greatly appreciated.
    JNIEXPORT jstring JNICALL Java_RNGInvoker_getRNG(JNIEnv *env, jobject obj)
         RNG R;
         unsigned char Data[128];
         R.gen_num(Data);
         char Data2[128];
         for(int i=0;i<RNG::RNG_RANGE;i++) {
              Data2=Data[i];
         return (*env).NewStringUTF(Data2);
    In Java,
    class RNGInvoker {
        public native String getRNG();
        static {
            System.loadLibrary("rng");
        public static void main(String[] args) {
            String temp = new RNGInvoker().getRNG();
            byte aa[] = new byte[128];
            int bb[] = new int[128];
            aa = temp.getBytes();
            for(int i=0; i<128; i++) {
                bb[i] = Integer.parseInt(String.valueOf(aa));
    System.out.println(aa[i] + ";" + bb[i]);

    C/C++ uses 'bytes' for 'char'. Java uses 'chars' in Strings, not bytes. You are generating a byte array. You are then trying to return a byte array as a String. When java uses a byte array to create a String it maps it using the default language of the system. This might or might not lead to changes in actual values.
    If you want to generate chars then figure out what the valid chars are for the range and language you are using.
    If you want a byte array then return that not a String.

  • Iteration a signed integer and not an unsigned integer, why?

    i was just wondering if there is a reason for keeping the iteration variable/indicator of a loop a signed 32 bit integer.
    it is never going to take a negative value.. then why signed; unsigned could have served the purpose
    Message Edited by Ujjval Shah on 07-08-2009 09:21 AM
    Solved!
    Go to Solution.

    Remember that array sizes are limited to I32 (the "size" input to initialize array is I32, the output of Array size is I32, etc), so running a FOR loop more than 2^21 times is not even possible (N is also I32).
    While loops can of course run forever, so if you need to increment a counter more than 2^31 times, you can use a shift register with U64, for example. However, don't even try to autoindex an output tunnel of such a loop, you're almost guaranteed to run out of memory before you reach the limits of I32.
    Using array indices as I32 has several advantages. For example sometimes you need an invalid index (Integers don't have NaN!), so having a negative number is very useful. For example if you use "search array" and no match is found, the output is -1.
    I suspect in the very long run these things will change. In another decade, all OSs will be 64bit or more and RAM will be mesured in TB. LabVIEW will need to evolve too to keep up. 
    LabVIEW Champion . Do more with less code and in less time .

  • Writing double and unsigned integer to serial port

    Hi all
         I have a basic question.  I am trying to write a double or unsigned intger to serial port.  Is it possible to do so?  If it is he case, how do I do it?
    Thank you very much.
    Best
    Hideya

    Hideya,
    The serial port sends one text character at a time. So you must convert your numeric value to a text or string representation and then send the string.
    LabVIEW has several functions on the String palette for numeric conversions. You must decide how to represent the number as text, floating point or exponential notation, number of significant digits, and other formatting issues. These may be dependent on what will be done with the data after being sent.
    Lynn

  • Convert unsigned integer to IEEE float

    Hello,
    Is there a typecast function in CVI that would convert 2 unsigned integers to IEEE loat?
    eg:
    1st value MSB:  50588
    2nd value LSB: 16425
    Actual reading:  -5000.02
    Thanks.
    TN
    Solved!
    Go to Solution.

    You just need to do some pointer manipulation to build your float.
    But you need to be aware of the size of the data types you're using.  Based on your example values, it looks like you are using the IEEE single precision format, which is 4 bytes.  In 32 bit operating systems, the unsigned int is also 4 bytes.  So you can't combine two unsigned int into an IEEE single without casting them as short ints, which are 2 bytes each.  You would need to check if the value in your unsigned int will fit in an unsigned short before casting it.
    You can play with the sizeof() function to see the data type sizes on whatever platform you're using.
    Here are a few lines of code the combine your example values to produce the expected result.
    #include <ansi_c.h>
    #include <utility.h>
    main()
     // allocate room for myFloat (IEEE single precision)
     float myFloat;
     // create pointers to the two words in the IEEE single precision format
     unsigned short *pMSW, *pLSW;
     // move the pointers to the first and second word in your float
     pLSW = (unsigned short *) &myFloat;
     pMSW = pLSW +1;
     // initialize the word values
     *pMSW = 50588;
     *pLSW = 16425;
     // print everything out
     printf("MSW: %d\tLSW: %d\tIEEE Single: %f\n", *pMSW, *pLSW, myFloat);
     // wait for a response
     printf("Press any key to continue...\n");
     GetKey();
    Here's a link to a discussion on going the other way, which has a sample program and links to more IEEE format info.
    http://forums.ni.com/t5/LabWindows-CVI/How-to-convert-a-number-to-32-bit-binary-or-Hex/m-p/977159#M4...

  • Cast(NULL as  INTEGER  ) - Problem

    Hello,
    Can any body explain me why there is a sub Query here. c3 is suppose to be Count(T263127."ROW_WID")
    select distinct D1.c1 as c1,
    D1.c2 as c2,
    cast(NULL as INTEGER ) as c3
    from
    (select distinct T31796."NAME" as c1,
    T325219."X_OPPTY_NAME" as c2
    from
    "W_OPTY_DX" T325219,
    "W_ORG_D" T31796 left outer join "W_ORG_DX" T262715 On T31796."ROW_WID" = T262715."ROW_WID",
    "W_REVN_F" T32385,
    "W_OPTY_DX" T263127
    where ( T31796."ROW_WID" = T32385."PR_ACCNT_WID" and T32385."OPTY_WID" = T263127."ROW_WID" and T32385."OPTY_WID" = T325219."ROW_WID" and T263127."X_ACTIVE_FLG" <> 'D' )
    ) D1
    order by c1, c2
    Thanks

    Thanks guys......i just missed a Complex join :(

  • Integer problem

    How can this code throw ClassCastException:
    'loginservlet
    int id = rs.getInt(1);
    session.setAttribute("user", new Integer(id));
    'jsppage after login
    String user;
    user = (String) session.getAttribute("user");It throws:
    Exeception: java.lang.Exception: java.lang.ClassCastException: java.lang.IntegerAndreas

    Session attribute user is set so the user only recive the posts from database that matches the users id. It�s a form of validation on requests.
    String sql = "SELECT * FROM [URLS] WHERE [IdUser] = " + userid +" ORDER BY [UrlName] ASC"; Here UserId should be the the session attribute user.
    Andreas

  • Unsigned int to integer conversion

    Hi,
    I have an unsigned integer column in my database table. If I try to retreive the value of the column using resultset.getInt() I'm getting "Numeric value overflow" error as it exceeds the INT_MAX value.
    For eg., if the column value : 4294967295, the expected value from resultset.getInt() is -1 or Numeric Value Overflow error ?
    Is it valid to retrieve the value using getInt() or should I use getLong()?.
    Kindly Clarify.
    Thanks,
    Radhika.

    use getLong

  • ACS v5.2 - Unable to update User integer attributes through File Operations

    Hi,
         I have created some internal users on ACS v5.2 and added some Unsigned Integer attributes for each user. I am trying to do a bulk update of these integer attributes using the File Operation facility. However no matter what number I put on the import template it doesn't get updated and displays a "0" in the user config.
    The import template is validated successfully with no errors and also the string attributes are updated correctly.
    There is a sort of work around of deleting the users and adding them back in with the updated values. But this is not feasible as it would reset their passwords. I have also tried saving the csv file in Open Ofifce instead of Excel
    Has any one else come across this problem?
    (I am unable to see this issue in the Release notes or Bug tool kit although there is a similar issue when updating devices in CSCth68051)

    Hi,
         Thanks for the reply. I have managed to recreate the problem to show you but it is a bit more complicated than I first thought. The problem only occurs when the integer attributes are added after the user is created.
    I created a dummy user. The MTL and TLS attributes were present before the user was added. I then added the XXX and ZZZ attributes afterwards and assigned them default values. The default values show up in the GUI config.
    However when I export the database to a csv file only the values of the MTL and TLS attributes show up in the export file:
    I then downloaded an import template and updated the integer values for TLS,MTL, XXX and ZZZ for the dummy user:
    The file imports successfully with no errors. However, when I display the user config only the MTL and TLS attributes have changed. The XXX and ZZZ attributes have stayed the same.
    I thought it might be because I was assigning a default value of 0 to the new attributes but I assigned ZZZ a default value of 1 and the same thing occurred.

Maybe you are looking for