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

Similar Messages

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

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

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

  • 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

  • Hi all! I was updating the software on i pad to ios6, update was interrupted(apple update server is unavailable...). iTunes Diagnostics shows that "secure link to I tunes store failed". I use Windows 7 Home Premium 64 bit. Can anybody help please?

    Hi all! I was updating the software on i pad to ios6, update was interrupted(apple update server is unavailable...). iTunes Diagnostics shows that "secure link to I tunes store failed". I use Windows 7 Home Premium 64 bit. Can anybody help please?
    The following was done so far:
    1. Windows Firewall - new rule created for itunes.
    2. iTunes - latest version installed.
    3. LAN setting : automatic detection of proxy is enabled;
    4. iTunes diagnostics shows:
    Microsoft Windows 7 x64 Home Premium Edition (Build 7600)
    TOSHIBA Satellite L655
    iTunes 11.0.2.26
    QuickTime 7.7.3
    FairPlay 2.3.31
    Apple Application Support 2.3.3
    iPod Updater Library 10.0d2
    CD Driver 2.2.3.0
    CD Driver DLL 2.1.3.1
    Apple Mobile Device 6.1.0.13
    Apple Mobile Device Driver 1.64.0.0
    Bonjour 3.0.0.10 (333.10)
    Gracenote SDK 1.9.6.502
    Gracenote MusicID 1.9.6.115
    Gracenote Submit 1.9.6.143
    Gracenote DSP 1.9.6.45
    iTunes Serial Number 003FB880034B7720
    Current user is not an administrator.
    The current local date and time is 2013-04-23 11:01:14.
    iTunes is not running in safe mode.
    WebKit accelerated compositing is enabled.
    HDCP is supported.
    Core Media is supported.
    Video Display Information
    Intel Corporation, Intel(R) HD Graphics
    **** External Plug-ins Information ****
    No external plug-ins installed.
    iPodService 11.0.2.26 (x64) is currently running.
    iTunesHelper 11.0.2.26 is currently running.
    Apple Mobile Device service 3.3.0.0 is currently running.
    **** Network Connectivity Tests ****
    Network Adapter Information
    Adapter Name:          {1CB5BBC2-8124-4664-899A-CE0A4683E3B4}
    Description:          Realtek RTL8188CE Wireless LAN 802.11n PCI-E NIC
    IP Address:          0.0.0.0
    Subnet Mask:          0.0.0.0
    Default Gateway:          0.0.0.0
    DHCP Enabled:          Yes
    DHCP Server:
    Lease Obtained:          Thu Jan 01 08:00:00 1970
    Lease Expires:          Thu Jan 01 08:00:00 1970
    DNS Servers:
    Adapter Name:          {8140112A-43D0-41D6-8B36-BE146C811173}
    Description:          Atheros AR8152/8158 PCI-E Fast Ethernet Controller (NDIS 6.20)
    IP Address:          10.5.7.196
    Subnet Mask:          255.255.0.0
    Default Gateway:          10.5.0.1
    DHCP Enabled:          Yes
    DHCP Server:          172.18.255.2
    Lease Obtained:          Tue Apr 23 10:14:40 2013
    Lease Expires:          Tue Apr 23 22:14:40 2013
    DNS Servers:          121.97.59.7
                        121.97.59.2
                        121.97.59.3
    Active Connection:          LAN Connection
    Connected:          Yes
    Online:                    Yes
    Using Modem:          No
    Using LAN:          Yes
    Using Proxy:          No
    Firewall Information
    Windows Firewall is on.
    iTunes is NOT enabled in Windows Firewall.
    Connection attempt to Apple web site was successful.
    Connection attempt to browsing iTunes Store was unsuccessful.
    The network connection timed out.
    Connection attempt to purchasing from iTunes Store was successful.
    Connection attempt to iPhone activation server was successful.
    Connection attempt to firmware update server was unsuccessful.
    The network connection timed out.
    Connection attempt to Gracenote server was successful.
    The network connection timed out.
    Last successful iTunes Store access was 2013-03-22 10:05:31.
    @@@. iTunes IS ENABLED THROUGH THE FIREWALL , even though diagnostics says "NOT enabled"

    hours after the first post i somehow got this to work. dont know how, but i do tried the dns clear cache, the clear host file, oh and i did the check automatically detech dns AND THEN se-check it again before i got this to work.

  • I am using Windows 7 Home Premium 64-bit OS.  I've never had this problem before... today I opened iTunes and it prompted me to download the newest version.  I use iTunes all the time and have updated it multiple times with no issues.  During the installa

    I am using Windows 7 Home Premium 64-bit OS.I've never had this problem before... today I opened iTunes and it prompted me to download the newest version.  I use iTunes all the time and have updated it multiple times with no issues.  During the installation process it gave me an error message that said: 
    Runtime error! 
    Program C:\Program Files\iTunes.exe
    R0634
    An application has made an attempt to load the C runtime library incorrectly.
    Please contact the application's support team for more information.
    I quit the installation, uninstalled iTunes and rebooted my computer.  I now receive a similar message with a slight difference:
    Runtime error! 
    Program C:\Program Files (x86)...
    R0634
    An application has made an attempt to load the C runtime library incorrectly.
    Please contact the application's support team for more information.
    I did not leave anything out from the error message.  It doesn't point to a specific file, it just ends with "(x86)..."  Every time I boot up my computer, this error message pops up on my desktop.
    How do I repair this issue?  I have found multiple suggested solutions but am unsure which one is the best, and I don't want to try a bunch of different things for fear I may make the problem worse.  I would like to try and fix this myself if possible but I need to know if that is really possible or if I need to take my computer to someone for repairs.  Any suggestions will be greatly appreciated!!

    Hi lustyln,
    I'm having a little trouble understanding all of what you are trying to explain. From what I can tell, it sounds like your PC has a lot of software problems and you want to know what is supposed to be there and what isn't.
    For reference, here are your product specifications:
    http://h10025.www1.hp.com/ewfrf/wc/document?cc=us&dlc=en&docname=c01893242&lc=en&product=4043282
    To get your PC software back to how it was when it was first purchased, run a system recovery:
    http://h10025.www1.hp.com/ewfrf/wc/document?cc=us&dlc=en&docname=c01867418&lc=en&product=4043282
    I hope this helps.
    ...an HP employee just trying to help where I can, but not speaking on behalf of HP.

  • I just planned to install windows 7 on my MBP Mid-2012 using VMware Fusion,so i am bit panic about viruses and malware's affecting through vmware,is there any way to avoid from this??

    i just planned to install windows 7 on my MBP Mid-2012 using VMware Fusion,so i am bit panic about viruses and malware's affecting through vmware,is there any way to avoid from this??

    usamasheikh wrote:
    virus protection in vmware or on my running OS X 10.8.2??plz help me out
    First, you can install Microsoft's Security Essentials in the Win 7 VM and keep it up-to-date. Second, you can turn off Sharing in Fusion's System Settings to keep the VM environment separate from your Mac. Third, you can look into Sophos Anti-Virus http://www.sophos.com/en-us/products/free-tools/sophos-antivirus-for-mac-home-ed ition/download.aspx for the Mac host.

  • I used this iphone wire for a bit, it worked perfectly but then suddenly i couldnt charge my phone and it stopped working completely. ive tried many other wires but they dont seem to work as well. im starting to get really frustrated

    i used this iphone wire for a bit, it worked perfectly but then suddenly i couldnt charge my iphone 5  and it stopped working completely. ive tried many other wires but they dont seem to work as well. im starting to get really frustrated and im really unsure of whats the case. i really really need help with this. please help asap!!

    Presuming you are using a wall charger - it would seem that your battery needs to be looked at in an Apple store

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

Maybe you are looking for

  • Settlement-Why local currency 3 did not be include in settlement by SAP?

    Dear All, Need your advice regarding issue bellow: I have post Accounting Document with zero amount in local currency(USD) and local currency2(USD), but no zero amount in local currency3(IDR). For better simulation, kindly find case bellow: Itm PK S

  • Graph in a subscreen area

    Hi Experts, How do you create a graph in a subscreen? I checked out transaction GRAL but all the graph charts popup in a separate screen. Moreover I do not want the BOXES internal table attached to the chart.  How do you suppress this functionality?

  • Can I add folders to mail on the iPAD?

    Just loaded 4.2.1 on my ipad. The mail only has in,sent and trash boxes. Can I add other boxes or folders to be able to sort my mail as I do on my mac.

  • Upate for Nokia 5800

    Hello When can my 5800 in danish be updated??? br - Peter

  • Discoverer & Query Builder 6.0

    Can I use Oracle Discoverer and Query Builder 6.0 with Oracle Financials database for quering the details ? How do i connect ? Will i have a connect string for oracle financials? If yes, where can i find the same ? Kindly reply