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

Similar Messages

  • 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));
    }

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

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

  • Weird problem using bitwise opertor

    Hi all,
    I have problem with >>> (bitwise logical right shift) operator.
    As an example, the result of this operator on 0x8000 value is not as I expect. As I read about this operator, the result of one bit logical right shift should be 0x4000 but the actual result is 0xC000, and as I see in my test applets there is no difference between >> and >>> operators. I tested this operator on both ST and Gemalto cards and the results were the same.
    short n=(short) 0x8000;
    short x= (short) n >>>1; //Here I expect 0x4000 but the actual result is 0xC000
    short y= (short) n>>1; //Here as I expect the result is 0xC000Would some body please explain such weird action of this operator?
    By the way, Is there any explicit operator for POWER operation in java card or I should use this bitwise operators instead?
    -Thanks a lot
    Edited by: bluefairy on Sep 16, 2010 12:50 AM

    It is quite simple if you know where to look. Open up your Java Card Virtual Machine specification, if you can find it.
    The >>> operator translates to the "sushr" bytecode.
    Let's see what that means...
    Forms
    sushr = 81 (0x51)
    Stack
    &hellip;, value1, value2 &minus;>
    &hellip;, result
    Description
    Both value1 and value2 must be of type short. The values are popped from the operand stack. A short result is calculated by sign-extending value1 to 32 bits (footnote 1) and shifting the result right by s bit positions, with zero extension, where s is the value of the low five bits of value2. The resulting value is then truncated to a 16-bit result. The result is pushed onto the operand stack.
    Footnote 1
    Sign extension to 32 bits ensures that the result computed by this instruction will be exactly equal to that computed by the Java iushr instruction, regardless of the input values. In a Java Card virtual machine the
    expression "0xffff >>> 0x01" yields 0xffff, where ">>>" is performed by the sushr instruction. The same result is rendered by a Java virtual machine.
    So... What does this mean ? This means that your variable is sign-extended to a 32-bit value (meaning that the sign bit is propagated), THEN the right shift is performed.
    See below my comments in the code.
    short n = (short) 0x8000;
    short x = (short) n >>> 1;
    // 0x8000 is extended to 0xFFFF8000
    // Right-shift by 1 bit --> 0xFFFFC000
    // Cast to short --> 0xC000Hope this helps.
    Cheers

  • Use realational operators in an SQL query??????

    does any one knows how to use realational operators in an SQL query??????
    i wud like to do something like
    select decode(2<3,sysdate,sydate +1) from dual
    but i know decode does not supports relational operators......
    thanx and Regards
    amyt

    You can use a CASE statement which does support relational operators, or if you must use DECODE, then you can use something like:
    SELECT DECODE(SIGN(2 - 3),-1,sysdate,sysdate - 1)
    FROM dual;The SIGN function returns -1 if the expression is < 0, 1 if the expression is > 0 and 0 if the expression is 0. This works for numeric comparisions. You can use the GREATEST or LEAST functions in a similar fashion for character comparisions.
    TTFN
    John

  • Decode function - using comparison operators

    Can I use comparison operators in a decode function such as below:
    select tasknum, title, esthrs, assigndate,
    decode(assigndate, < '04-OCT-04', '--') accum_hrs
    from assignment
    thanks.

    Found my answer.

  • Problem Using Relational Operators !!

    The code given under is not working corretly. The problem is stated as comments in the program.
    if(result.next())
    String temp_no=t_no.getText();
    String temp_nm=t_name.getText();
    String temp_result1= result.getString(2);
    String temp_result2= result.getString(3);
    if(temp_no!=temp_result1) // The condition is always true.Even if i give the same no & name as in database!! Why is it so?
    JOptionPane.showMessageDialog(cdFrame, new String("There Is No Disc With The Specified Number !!"));
    else
    if(temp_nm!=temp_result2)
    JOptionPane.showMessageDialog(cdFrame, new String("There Is No Disc With The Specified Name !!"));
    else
    upd.executeUpdate();     
    JOptionPane.showMessageDialog(cdFrame, new String("DATA HAS BEEN UPDATED !!"));
    else
    JOptionPane.showMessageDialog(cdFrame, new String("There Is No Such Disc As Stated In Old Data !!"));
    }                              The Program compiles properly and gives no runtime error. What's the problem!!

    yes dude, u can't use relational operators for objects.. its works only on simple data types..

  • Using comparison operators to solve several different mathematic​al expression​s is not clear

    Though I found LabVIEW very interesting , still some of its basic fundamentals are not clear, like using comparison operators (>,<,..) for solving different
    mathematical expressions. Please give example showing how to use such operators in advanced mathematical problems.
    Best Regards,
    Allawi

    allawi1 wrote:
    What I am looking for is how to use such functions in selecting different mathematical expressions i.e..(working like logical if statement).
    You need to be more specific. A comparison operation IS like a logical IF statement and the result is either TRUE or FALSE.
    What do you mean by a "mathematical expression"? What do you mean by "different"? Can you give an illustrative example?
    If two alternative mathematical expressions should depend on the comparison, wire the comparison output to a case structure and place the two different expressions in their own case, for example.
    LabVIEW Champion . Do more with less code and in less time .

  • Problem in using relational operators in Data Templates

    Hi All,
    I have a query like following in data template type of Data set but I am not getting any data if I use simple < operator. Same query shows data in the database. Is there any other specific way of using relational operators in Data templates ? Please help in this regard
    <dataTemplate name="REVIEW_DATE" dataSourceRef="MY_DB">
         <dataQuery>
              <sqlStatement name="REVIEW_DATE">
                   <![CDATA[
    SELECT
    TABLE1.REVIEW_DATE
    FROM TABLE1 TABLE1 , TABLE2 TABLE2
    WHERE
    TABLE1.COLUMN1 = TABLE2.COLUMN2
    AND TABLE1.REVIEW_DATE < TABLE2.CURRENT_DATE]]></sqlStatement>
         </dataQuery>
         <dataStructure>
              <group name="REVIEW_DATE" source="REVIEW_DATE">
                   <element name="REVIEW_DATE" value="REVIEW_DATE"/>
              </group>
         </dataStructure>
    </dataTemplate>Thanks a lot !
    -Sookie

    solved after watching www.youtube.com/watch?v=FCujba8euWc
    thanks to all

  • Creating measure using set operators in BO Xi 3.0

    Hi All,
    I am trying to create a measure like this in BO XI 3.0 Designer.
    Select count(*) from
    select id from table1 where Name=<Prompt Value>
    INTERSECT
    select id from table1 where Name=<Prompt Value>
    But I don't know how to use set operators in Designer.
    Can someone please help or any pointer would help.
    Thanks,
    Kuldeep
    Edited by: Kuldeep Chitrakar on Apr 2, 2009 4:06 PM

    Create a derived table with same SQL and drag the table into universe pane to create object.

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

  • Additions with out using arithematical operators

    HI i have problem in java programming thatis how can i do additions and substractions with out using + ,-*(arithematical operators) in java

    make a guess
    its most probably home work
    But one has to wonder why this question is in the servlet forum

Maybe you are looking for

  • Can't sync from iTunes to iPhone, get 'iTunes has stopped working' message

    2 messages appear when I try to sync music (have tried a few times over the last few weeks and still having the same issue). I have no music now on my iPhone! I reverted to factory settings (as advised) then started again. Everything worked ok apart

  • External sample clock with pulse width measurement

    Dear all, I am using a NI 6220 board (programming with ANSI C) and would like to perform a "single pulse-width measurement" using an external gate signal and an external signal as source. Using the  "DAQmxCreateCIPulseWidthChan" command the program a

  • Code for radio button is not working plz help

    checkboxes are working fine but when i put radio code submit button does nothing plz help thanks in advance <%@ page language="java" contentType ="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" import= "java.sql.*,java.io.*,com.anaghan.MyBe

  • MDM tool for SAP PM

    Hi all, I need to know if there's any Master Data management tool (like MDG)? Preferably SAP product. NRX Asset Hub is one which my client is using but it may not fulfill the complex requirement of client. Best Regards, Anish

  • Checking for Oracle Home incompatibilities ...

    While installing oracle client 10.2.0.4. I came across this error. See below Checking the Components installed in Oracle Home Check complete. The overall result of this check is: Passed ================================================================