Bitwise operators on Long

Can I operate the bitwise operators e.g. on long?
i.e.
long l1;
long l2 = l1<<32;
Thanks

I don't see why not. Have you thought of trying it. It seems like it would be a simple test.

Similar Messages

  • How do Bitwise Operators work?

    Hi everybody
    I know a little bit of bitwise operators and I am getting some problems working with them.
    For example, imagine the byte 0x42 (Or 01000010). Now I want to build a long having this byte on the first position starting from the left so I try the following code:
    long l = 0x42 << 56;However, this operation seems to work like if I have written:
    long l = 0x42 << 24That is, the new long is a String of only 32 bits. Why does this command ignore the first 32 bits? Any ideas?

    > On a small tangent, I asked this question yesterday:
    what does this program output?
    Guess, then copy and run to see if you were right.
    public class PartyPretzel {
    public static void main(String[] args) {
    System.out.println(12345 + 5432ll);
    Wauu. I would have bet my hand saying that the result will be 66666 and it is 17777. And the reason for this is....

  • Bitwise operators in XSLT:-

    Hi ,
    Does XSLT has support for BITWISE operations, If so Can you please help me out of that >
    If not , Is there any other way to apply BITWISE logic to the flow in the BPEL.
    I tried it using Java Embedded activity in the BPEL, but I am getting the following Exception SCAC-50012,tried referring to this Exception, but not able to get the exact view of that error., as this activity in the BPEL doesnt have JAVA editor I am not able to point out the same.

    Hi everybody,
    I have the following queries in JAVA.
    1)Is "Operator Overloading" is nothing but
    but "Method Overloading" in Java?There's no operator overloading in Java. For example + can't be changed to mean something else.
    2)Regarding BitWise Operators, i just wanna have
    have an simple example abt the usage of bitwise
    operators. i.e., in real world where we will be using
    these ?Just one example of many is the use of bitwise XOR in simple encryption/decryption. The scheme is called XOR scrambling.
    byte key = 0x77; // a key byte 0101 0101
    byte any = ......; // any byte to be scrambled
    byte scramble = key ^ any; // the scrambled byte
    byte unscramble = key ^ scramble; // unscramble == any, the original byte is back againIt builds on the fact that if you XOR any byte with a bit pattern (key) two times you get the original byte back again.

  • Bitwise Operators .. stupid question ?

    I have a HashMap which contains Strings.. The String are actually numbers.
    I want to use Bitwise operators of and or, xor on them... How so I do it?
    I want to say result = string1 and string2...... I am not sure how stupid this sounds... but I am sure I am too close to it....

    Example answer to your original question, wanna:
    Hashtable<Object, String> ht = new Hashtable<Object, String>();
    ht.put("twenty eight", "28");
    ht.put("five", "5");
    ht.put("twenty", "20");
    System.out.println(Integer.valueOf(ht.get("twenty eight")) & Integer.valueOf(ht.get("five")) & Integer.valueOf(ht.get("twenty")));Which, of course, prints "4" to standard out. You're best off using a Hashtable<Object, Integer>, though.
    In answer to your second question,
    ~ is indeed the compliment operator. E.g:
    System.out.println(1 + ", " + (~1));
    prints "1, -2", as you might expect.

  • Bitwise operators--please explain ?

    I've been reading about bitwise operators, and I get the concept about what they do. My question is why would you ever need an operator like this? When do you need to manipulate memory like this? I can't concieve of a use for it, but obviously there must be one. Just curious--thanks.

    Hi...
    when you have packed different values into one variable...
    hmmm... for example, when you use RGB color system, normally, you have the 3 values of the colors in just one 32 bit integer value, in this format:
    XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX
    R G B
    where X = one bit... (an integer is 32 bit size)...
    then, you need bitwise operators for extract the values for each color, something like this:
    int color = something that obtain the value of the pixel...
    int r = (color & 0xFF0000)>>16;
    int g = (color & 0xFF00)>>8;
    int b = color & 0xFF;
    another use of the bitwise operators is in some devices with digital inputs/outputs, where the values of that are given packed in just one integer value (or another type)....
    I hope this helps you...
    ps. sorry for my english...
    EOF

  • Using bitwise operators to swap individual bits

    I'm able to set or clear individual bits using masks, however I'm trying to figure out how I could go about swapping two bits using bitwise operators but I haven't been able to figure it out. For example, say I had int x = 37 which is 100101 in binary and I wanted to swap the 2nd and 3rd bits I'd like to get 100011 when I use Integer.toBinaryString(x) after performing some bitwise operations on x to swap bits around. Any suggestions ?

    How about something like this? A preliminary test seemed to work.
    class BitSwap2 {
      public static void main(String[] argv) {
        int x = 37;
        System.out.printf("Binary: %s\n", Integer.toBinaryString(x));
        swapBits(x, 2, 3);
      private static void swapBits(int x, int a, int b) {
        if(a == b) {
          System.out.printf("Nothing to swap.\n");
          return;
        int first = (x & (1<<(a-1)));
        int second = (x & (1<<(b-1)));
        // zero them out from the original so that we can swap them
        x ^= (first | second);
        if(a > b) {
          int diff = (a - b);
          x |= (first >> diff);
          x |= (second << diff);
        } else {
          int diff = (b - a);
          x |= (second >> diff);
          x |= (second << diff);
        System.out.printf("Binary: %s\n", Integer.toBinaryString(x));
    }

  • Using bitwise operators

    hi,
    I'm new to java.. Still learning ....I hope some one would help me here ...
    I wanted to check how bitwise operator works... tried all operators .. but the NOT operator seems to work in a different way ..could someone brief me ...
    ~2 -2
    but the program gives a result -3.
    pls explain how it works

    It reverses all the bits in the number, that is: 0 becomes 1 and 1 becomes 0. And because the "two's complement"-rule defines negative numbers as "-x" = ~x + 1, you get ~x = -(x+1). 2 = 0000 0000 0000 0000 0000 0000 0000 0010
    ~2 = 1111 1111 1111 1111 1111 1111 1111 1101
       = -(0000 0000 0000 0000 0000 0000 0000 0010 + 1)
       = -3

  • Bitwise operators

    what is difference between >> and >>> right shift with zero fill any example ?

    First, read this: http://en.wikipedia.org/wiki/Two%27s_complement
    Given that, you'll understand that the high bit is the sign bit. There are two ways to shift right:
    1. Bitwise shift-right (shift-right zero-fill).
    2. Arithmetic shift-right (shift-right sign-extend).
    The first option fills the high bits with zero as you shift right.
    The second option performs sign-extension, which means the high bit is used to fill in the bits that were shifted right.
    Example:
    8-bit number: 10001010, high bit is 1
    Shift it right 1 position: n1000101 (the "n" represents the missing bit)
    Fill in the missing high bit with the old high bit (1): 11000101

  • Bitwise Operators & IP Addresses

    I am trying to determine an ip address class type ie:
    Class A - 0 followed by 7 bits
    Class B - 0 followed by 6 bits
    Class C - 110 followed by 5 bits
    The IP address & Subnet Mask are entered by the user
    By ANDING the IP address and the subnet mask I have to determine whether the result is a class A, B or C IP address. I also have to return the Subnet address.
    What is the approach I should take to doing this? Any help would be greatly appreciated!
    Cheers!

    Not exactly what you are looking for, but think I got it. I'm not Cisco Certified, but I think this seems to work. This is an IP address filter based on network prefix and netmask. Class C is shown. To filter Class A just make netmask 255.0.0.0, etc....
    String testaddr = "10.1.0.137";
    String netprefix = "10.1.0.0";
    String netmask = "255.255.255.0"; //Class C netmask
    int [] addr_arr = {0,0,0,0,0,0,0};
    int [] ntmsk_arr = {0,0,0,0,0,0,0};
    int [] prefx_arr = {0,0,0,0,0,0,0};
    for (int indx = 4; indx !=0; indx = indx - 1)
    addr_arr[indx] = Integer.parseInt(testaddr.substring(testaddr.lastIndexOf(".")+1));
    ntmsk_arr[indx] = Integer.parseInt(netmask.substring(netmask.lastIndexOf(".")+1));
    prefx_arr[indx] = Integer.parseInt(netprefix.substring(netprefix.lastIndexOf(".")+1));
    if (testaddr.indexOf(".")!=-1)
    testaddr =testaddr.substring(0,(testaddr.lastIndexOf(".")));
    netprefix = netprefix.substring(0,(netprefix.lastIndexOf(".")));
    netmask =netmask.substring(0,(netmask.lastIndexOf(".")));
    if ( (addr_arr[indx] & ntmsk_arr[indx]) == prefx_arr[indx])
    //System.out.println( "allow this packet" + addr_arr[indx] );
    }else {return;} //quit here you failed filter test
    //continue if you got this far......
    System.out.println( "allow this packet" + addr_arr[indx] );
    That was fun.

  • Bitwise Operators - Different Output ?

    Hello !
    Can anyone please as to why these two different programs are giving different values ? Both are using Right
    Shift Operator >>> .
    The first shifts right the value a set to -1 to 24 bit positions giving a = 255 . But with the second program
    doing the same in a loop we start getting zero from the 9 iteration and continues till 24 ( and onwards ) . Why
    are we not getting the same value for a from the two programs ?
    // Right Unsigned Shifting : >>> ( Shift Right zero fill )
    class RUnsignShift {
    public static void main(String args[]) {
    int a = - 1 , b = 0 ;
    System.out.println("\nDemonstration : Right shift zero fill Operator >>> ");
    System.out.print("Original value int a = " + a +" ") ;
    System.out.println("Bit pattern : 11111111 11111111 11111111 11111111");
    b = a ;
    a = a >>> 24 ;
    System.out.print("a = -1 >>> 24 (Zero-fill) bit positions a = " + a +" ");
    System.out.println("Bit pattern : 00000000 00000000 00000000 11111111");
    b = b >> 24 ;
    System.out.print("b = -1 >> 24 (Sign Ext.) 24 bit positions b = " + b +"\n");
    SECOND PROGRAM
    class RUnsignShift2 {
    public static void main(String args[]) {
    int a = -1 , i ;
    System.out.println("Demonstration : Right shift zero fill Operator >>> ");
    System.out.print("Original value int a = " + a +" ") ;
    System.out.println("Bit pattern : 11111111 11111111 11111111 11111111");
    for(i = 0 ; i < 10 ; i++) {
    a = a >>> i ;
    System.out.println("a >>> " + i + " (Zero-fill) bit positions a = " + a +" ");
    //System.out.println("Bit pattern : 00000000 00000000 00000000 11111111");
    }

    NADEEMUDDIN wrote:
    a = a >>> 24 ;
    SECOND PROGRAM
    for(i = 0 ; i < 10 ; i++) {
    a = a >>> i ;
    System.out.println("a >>> " + i + " (Zero-fill) bit positions a = " + a +" ");
    //System.out.println("Bit pattern : 00000000 00000000 00000000 11111111");
    }The problem is that in your second program, a gets shifted with i meaning first time is a >>> 0, second time a >>> 1 etc. and all that it's equivalent with a >>> 45 at the end of the loop.
    To have the same results some changes must occur:
    for(i = 0 ; i < 24 ; i++) {
    a = a >>> 1 ;
    System.out.println("a >>> " + i + " (Zero-fill) bit positions a = " + a +" ");
    //System.out.println("Bit pattern : 00000000 00000000 00000000 11111111");
    }So in the final pass (24th) the a = a >>> 24.
    Cheers!

  • Int (32 bits) - byte (8 bits) using bitwise operators

    Hi!
    I am storing a 16-bit value into a 32-bit integer and trying to extract the Most Significant 8-byte and Least Significant 8-byte as follows:
    int n = 129;
    byte msb = (byte)(((byte)(n>>8))&0xff);
    byte lsb = (byte)(n&0xff) ;
    System.out.println ("msb = "+msb+" lsb = "+lsb);
    My msb is "0" and my lbs becomes "-127".
    The above code works correctly for positive numbers but for signed values (like >129-255), my lsb comes to a negative number.
    How should the above code be to handle the lsb?
    Thanks,
    x86

    My msb is "0" and my lbs becomes "-127".
    The above code works correctly for positive numbers
    but for signed values (like >129-255), my lsb comes to
    a negative number.
    How should the above code be to handle the lsb?
    Your code works fine. Are you wondering why an int value of 129 shows up as a msb of 0 and a lsb of -127? It's because byte values are signed and a bit pattern of 10000001 is equal to -127.

  • Bitshift operator and bitwise operators throwing errors

    Hi,
    I am using Java 1.4 on JDeveloper.
    When I try to complie following piece of code, its gives error:
    package myOtherPackage;
    class BitDemo {
        public static void main(String[] args) {
            int bitmask = 0x000F;
            int val = 0x2222;
            // prints "2"
            System.out.println(val & bitmask);
    }Error: method >>(java.lang.String, int) not found in class myOtherPackage.BitDemo.
    Kindly help me on this....

    Sorry ,
    Compilation completes but running it gives error when I keep this class in package. when took it out of package and defined as separate class, it runs fine...
    Error :
    Error(11,48): method &(java.lang.String, int) not found in class myOtherPackage.BitDemo
    Please look at error description. METHOD & .
    Edited by: J2EE_Life on Dec 26, 2011 8:56 AM
    Edited by: J2EE_Life on Dec 26, 2011 8:56 AM

  • SCJP prep help -- bitwise bad boys?

    Hi,
    I'm studying for SCJP so obviously one of the details I have to brush up on are the oft-unused bitwise operators: & | ^ ~
    I'm wondering if there are any mental techniques to using these in your head. Instead of literally writing out the number in binary, performing the comparison, and then re-converting back to decimal.
    Similar to how in grade school we learn that you can take a shortcut of multiplying two long numbers:
    34563
    x 24
    and do these steps:
    3 * 4 = 12, carry the 1
    6 * 4 = 24, add the 1 is 25, carry the 2
    5 * 4 = 20, add the 2 is 22, carry the 2
    4 * 4 = 16, add the 2 is 18, carry the 1
    3 * 4 = 12, add the 1, it all equals 138252
    next line
    then pad a zero on the right
    3 * 2 = 6
    6 * 2 = 12, carry the 1
    5 * 2 = 10, add the 1 is 11, carry the 1
    4 * 2 = 8, add the 1 is 9
    3 * 2 = 6, it all equals 691260
    altogether the answer is 691260 + 138252 = 829512
    In other words, while it's not feasible to add 34563 to itself 24 times (23 actually), there is a trick to figuring it out. Is there something like that for bitwise operators?
    Thanks.

    Thanks -- I finally collated some good tips a few days after I posted that here, with some help from local LUGgers. I'll post them here for the archives:
    Would you mind posting a summary of the helpful tips, tricks, and
    shortcuts sent your way? I'm rather interested in understanding this
    stuff a little better myself.Sure. In fact, they say you really know something well when you can
    explain it to someone else, and this gives anyone a chance to correct me
    if I'm wrong in what I think I know. Here's some of the things I
    learned, combined with what I had already learned from my book (please
    do correct me if I'm wrong):
    1. The unary bitwise NOT operator (~) has a shortcut, but one which
    only works when two's complement is in effect. On systems in which
    one's complement is in effect, it doesn't work. The shortcut is that
    any number n has a bitwise NOT of -n - 1. So
    ~5 == -6
    ~-12 == 11
    Because I'm fortunate enough to be working in Java where you're writing
    for only one platform (the JVM, which has a spec), I don't have to worry
    about exceptions to this for the test.
    2. Other than the NOT operator, the bitwise operators are binary
    operators, working on pairs of numbers. The bitwise AND operator
    returns a 1 for each pair of bits that are both 1.
    So in the case of
    11001 & 10011
    the result is 10001 (because only the first and last digits are both 1).
    The bitwise OR (|) operator returns a 1 for situations in which either
    pair of bits has a 1.
    So in the case of
    11001 | 10011
    the result is 11011 (because the only place in both numbers where there
    is no 1 is the third digit).
    The bitwise XOR (^) operator returns a 1 for situations in which either
    pair of bits, but not both, has a 1 (hence the name "exclusive OR", or XOR).
    So in the case of
    11001 ^ 10011
    the result is 01010 (because in the first, third, and fifth digits,
    either both numbers are 0 or 1).
    The short circuit operators AND (&&) and OR (||) work just like their
    regular counterparts except they stop evaluating once they "know" the
    result (AND stops evaluating if the first operand is false, and OR stops
    evaluating if the first operand is true).
    3. So my original question, "does anyone know any mental shortcuts for
    working with bitwise operators", should have been phrased as "does
    anyone know any mental shortcuts for converting decimal numbers to
    binary". The answer, which a couple of people provided, was that it's
    much easier to convert to binary (even if only in your head) when you
    are working from octal or hexadecimal, and that it's not too difficult
    to convert from decimal to octal or hexadecimal.
    Several ways were suggested:
    a) Convert the number to hex, then do the comparison a byte at a time in
    your head using a table:
    & 0x01 0x02 ... 0xff
    0x01 0x01 0x00 0x01
    0x02 0x00 0x02 0x02
    0xff 0x01 0x02 0xff
    b) Convert the number to octal using a simple recursive divide-by-eight
    solution:
    divide the number by eight, store the remainder as the low bit depth
    (rightmost number), then repeat the process with the quotient.
    123 / 8 = 15 remainder 3 -- 3 is rightmost digit (3)
    15 / 8 = 1 remainder 7 -- 7 is next to 3 (73)
    we don't divide 1 by 8 -- 1 is next to 7 (173)
    so 123 in octal is 0173
    From octal it's much easier to see the binary form of the number:
    1 7 3
    001 111 011
    And from binary it's much easier to do a bitwise calculation.
    c) Another way to convert to binary is to simply keep dividing by two
    and assigning 1 if there's a remainder and 0 if there isn't, then read
    in reverse to get the binary number:
    <quote>
    If a number is even, dividing it by 2 will have 0 remainder.
    If it is odd, dividing it by 2 will have a 1 remainder. Dividing
    by 2 is so easy that I, at least, can just write down a column of
    successive halvings, along with 1s and 0s for their oddness.
    459 1
    229 1
    114 0
    57 1
    28 0
    14 0
    7 1
    3 1
    1 1
    Reading from bottom to top, we again get 111001011. In this
    presentation you stop when the quotient is 1, since you've already
    written down the remainder that you'd get by dividing 1 by 2 when
    you write down the oddness. Remainder when dividing by 2 is easier
    than quotient.
    </quote>
    d) A final useful tip mentioned: as long as x is not zero,
    x & -x
    will always evaluate to a power of two, which means only one bit is set
    in the number (the least significant of the bits of x that were 1s).
    4. And everyone agreed that it's foolish to do these kinds of
    computations in your head when there's no good reason not to use a
    computer to do it. My personal preference is to use Python since the
    interactive interpreter works just like a calculator, though any
    scripting language should probably be able to handle the calculations.
    (Here's a quick sample:)
    |$ python
    |Python 2.2.2 (#1, Dec 31 2002, 12:24:34)
    |[GCC 3.2 20020927 (prerelease)] on cygwin
    |Type "help", "copyright", "credits" or "license" for more information.
    |>>> 12 & 14
    |12
    |>>> 12 | 14
    |14
    |>>> 12 ^ 14
    |2
    |>>> ~12
    |-13
    |>>> myResult = 0x5422CA66 & 458
    |>>> myResult
    |66
    |>>> hex(myResult)
    |'0x42'
    (hey, it wouldn't be a LUG without a little evangelism, would it? :)
    Much thanks to Bill, Jason, Kevin, and YATArchivist.
    Erik

  • I have to generate a 4 char unique string from a long value

    I got a requirment
    I have to generate a 4 char unique string from a long value
    Eeach char can be any of 32 character defined has below.
    private static final char char_map[] = new char[]{'7','2','6','9','5','3','4','8','X','M','G','D','A','E','B','F','C','Q','J','Y','H','U','W','V','S','K','R','L','N','P','Z','T'};
    So for 4 char string the possible combination can be 32 * 32 * 32 * 32 = 1048576
    If any one passes a long value between 0 - 1048576 , it should generate a unique 4 char string.
    Any one with idea will be a great help.

    Well, a long is 64 bits. A char is 16 bits. Once you determine how you want to map the long's bits to your char bits, go google for "java bitwise operators".

  • What's bitwise for?

    I read the little thing for "Shift and Logical Operators" and I'm a tad confused. What exactly can you do with them? Very odd little buggers...

    There are several things that bitwise shift and logical operators are useful for.
    The most obvious is to test individual bits (or as an extension of this, groups of bits) within an int, long, or other numerical type value. For instance, the AWT events use flags like this extensively. Let's examine java.awt.event.InputEvent's getModifiers() method.
    It returns an int value with various bits set to indicate which modifier keys (Shift, Ctrl, Alt, etc.) are depressed. One way to find out if the Ctrl key was pressed when the event was generated is to do this: (assuming this is your method implementing the KeyListener interface)
    public void keyPressed(KeyEvent event) {
      int modifiers = event.getModifiers();
      if (modifiers & KeyEvent.CTRL_MASK != 0) System.out.println("Ctrl is pressed");
    }The value of the CTRL_MASK constant is some value with only 1 bit set in it. (i.e., it is a power of 2.) So anding some value with CTRL_MASK will result in CTRL_MASK if the bit was set, or 0 if it wasn't, because all the other bits are false in the mask, so those are the only possible result of ANDing another number with it.
    So the reason for using a mask in cases like this instead of just a bunch of booleans reduces memory usage significantly. (I believe a boolean in Java takes up a full 32-bit word. Anyone care to confirm or deny this?)
    Bit operations are also extremely helpful when interfacing to a device, or calling native code, or reading data files, or processing image data.
    Secondly, bitwise shifts and mask operations are much faster ways to do divide, multiply, and modulo operations by powers of 2. For instance:
        n % 16 == n & 15     // 15 in binary: 1111, this just discards (=0) higher bits
        n % 256 == n & 255   // 255 in binary: 1111 1111, same: masks off high bits
        n / 2 == n >> 1
        n / 4 == n >> 2
        n / 8 == n >> 3
        n / 16 == n >> 4
        n / 256 == n >> 8
        n * 2 == n << 1
        n * 4 == n << 2
        n * 8 == n << 3
        n * 16 == n << 4
        // etc.Hope this provides some insight into the common uses of bitwise operators. Understanding binary arithmetic turns out to be extremely useful. It's worth spending some time with the various operators and learning how they work.
    (Also, I didn't mention the lesser-known '>>>' operator, known as the unsigned right shift. Of course if you don't have a good grasp on twos-complement binary notation, the purpose of this operator won't make sense. I don't know what a good source on this subject is off the top of my head, but if you're interested, I'm sure someone can recommend something.)
    Cheers,
    Colin

Maybe you are looking for

  • Jabber not support p2p audio on WebEx Connect.

    Hi, everyone. We have received complaints from customers in the WebEx Connect Client peer-to-peer audio functionality. We know Cisco's announcement, after April 3, 2015, a customer has to use Jabber on WebEx Connect. But Jabber doesn't have the peer

  • Hmm, to the person who asked why the store carries cover versions...

    Not sure what caused that thread to disappear... Apple don't monitor these forums for feedback nor answer questions directly. You may send your thoughts to iTunes Feedback if you wish. There is a long tradition of different artists recording the same

  • New Non-ASM Standby Trying to use ASM during recovery

    Oracle 11.2.0.3 on RH6 x86_64. Cross-posting from oracle-l. We have a database on ASM. We want to migrate to filesystem storage on same host (Oracle ZFS). Recommended path from Oracle is to create a standby and then do a failover when ready. Simple e

  • JRE GIF Images Buffer Overflow Vulnerability

    Hello All, There is an exploit in the wild for a vulnerability covered here: http://www.securityfocus.com/bid/22085/exploit It is on the following site: (Caution! Visiting any page on this site will cause the exploit to be executed, and I'm not convi

  • How to enable some DFF segments on AR Trx form for specific context only

    I have a requirement to enable 3 of many DFF segments on AR Transactions line DFF for particular context only. I am not able to figure out how to achieve it. When we query for an Invoice and navigate to lines DFF I want these fields to be allowed to