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.

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

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

  • Casting int to a byte -- retreiving the lowest 8 bits

    Yo, thought i'd try to open up some debate on this topic. I wrote a data feed that needed to grab the lower 8 bits out of an int, so i wrote what i believed to be the standard way of doing this, which was effectively
    public static byte intToByte( int c ) {
            return (byte) (c & 0xff);
    }A colleague looking through my code asked whether the & 0xff was necessary, and did i believe that there was any value of c for which it made a difference, as he believed that this was equivalent to just
    return (byte)c; My immediate thought was worrying about byte in java being signed, and having data screwed up, so i ran some tests.. and on every value i tried (byte)c is indeed equivalent to (byte)( c & 0xff ).
    My argument was to be that (byte)( c & 0xFF ); is great code to read as a maintainer, because it;'s immediately obvious that you are strictly interested in the lowest 8 bits of the int, and nothing else is of importance, and a simple (byte)c; can look naive and make every developer looking at the code for the first time think it's incorrect.
    However, i knew his comeback would be that the datafeed has an overriding need for speed, so i ran some tests comparing the repeated operation of (byte)c to (byte)(c & 0xff ) over a range of 100,000 numbers (test repeated several times to obviate startup times). It turned out that doing the & 0xff added about 30% to execution time on my machine (java 1.5 on WinXP). That's quite a severe penalty for a very common operation! I think i'm going to change the code to cast straight to a byte and leave a big comment beforehand explaining how it's equivalent to (byte)(c & 0xff );
    This got me wondering how it was implemented in the core java libraries though, since OutputStream has a method to write a byte that actually takes an int parameter. How does this work? Most of the lowest level OutputStream implementations seem to end up going to native to do this (understandably), so i dug out ByteArrayOutputStream. This class does optimise away the & 0xFF and is roughly
        public synchronized void write(int b) {
                �
                buf[count] = (byte)b;
                �
        }No problems with that, so writing to these babies will be fast. But then i started wondering about the methods of DataOutputStream, which is heavily used by use for serialising (a great deal of) internal data flow. Unfortunately in this class there are a lot of redundant & 0xFFs:
    public final void writeShort(int v) throws IOException {
            out.write((v >>> 8) & 0xFF);
            out.write((v >>> 0) & 0xFF);
            incCount(2);
    public final void writeInt(int v) throws IOException {
          out.write((v >>> 24) & 0xFF);
          out.write((v >>> 16) & 0xFF);
          out.write((v >>>  8) & 0xFF);
          out.write((v >>>  0) & 0xFF);
          incCount(4);
    }[The v >>> 0 seems to be optimised out at runtime and i get no execution time difference between ( v >>> 0)  & 0xff that and ( v & 0xff ) so i got no problems with that]
    which again seems ok on inspection because the code looks tidy and clean and easy to understand, but i need to hit these things very heavily so would rather they were 30% faster than easy to read. Interestingly they've taken an entirely different approach for writing out a long value:
    public final void writeLong(long v) throws IOException {
            writeBuffer[0] = (byte)(v >>> 56);
            writeBuffer[1] = (byte)(v >>> 48);
            writeBuffer[2] = (byte)(v >>> 40);
            writeBuffer[3] = (byte)(v >>> 32);
            writeBuffer[4] = (byte)(v >>> 24);
            writeBuffer[5] = (byte)(v >>> 16);
            writeBuffer[6] = (byte)(v >>>  8);
            writeBuffer[7] = (byte)(v >>>  0);
            out.write(writeBuffer, 0, 8);
            incCount(8);
    }both using a private buffer field for the writing before squirting it all out, and not bothering to mask the lower 8 bits. It seems strange that writeLong appears optimised, but writeInt and writeShort are not.
    What does everyone else think? Are there any other heavy users of DataOutputStream out there that would rather have things written faster? I guess i'm going to be writing my own version of DataOutputStream in the meantime, because we're writing so much data over these and i'm in an industry where milliseconds matter.

    To my knowledge, in your situation, the & 0xFF is not necessary. I believe that the most common use of the mask in this case is actually to treat the lower 8 bits as an unsigned integer. For example:
    int value = 65530;
    int anotherValue = value & 0xFF; // anotherValue == 250Anyway, the case space is small enough that I just brute forced your problem. Under v1.5.0_07 on Linux, (byte)i and (btye)(i & 0xFF) are definitely the same:
    for (int i=Integer.MIN_VALUE;i<Integer.MAX_VALUE;i++)
        byte a = (byte)i;
        byte b = (byte)(i & 0xFF);
        if (a!=b) System.out.println(i);
    byte a = (byte)(Integer.MAX_VALUE);
    byte b = (byte)(Integer.MAX_VALUE & 0xFF);
    if (a!=b) System.out.println(Integer.MAX_VALUE);Perhaps the & 0xFF was in response to some older bug or other behavior.

  • Is there an easier way to convert bytes into bit(boolean) arrays?

    I am currently using this method to convert bytes into bit arrays:
    /*convert byte to int such that it is between 0-255 this is the bytes[] array
                        if ((bytes/128)==1)
                             bit[c+0]=true;
                        else
                             bit[c+0]=false;
                        if ((bytes[i]-bitInt[c+0]*128)/64==1)
                             bit[c+1]=true;
                        else
                             bit[c+1]= false;
                        if ((bytes[i]-bitInt[c+0]*128-bitInt[c+1]*64)/32==1)
                             bit[c+2]=true;
                        else
                             bit[c+2]= false;
                        if ((bytes[i]-bitInt[c+0]*128-bitInt[c+1]*64-bitInt[c+2]*32)/16==1)
                             bit[c+3]=true;
                        else
                             bit[c+3]= false;
                        if ((bytes[i]-bitInt[c+0]*128-bitInt[c+1]*64-bitInt[c+2]*32-bitInt[c+3]*16)/8==1)
                             bit[c+4]=true;
                        else
                             bit[c+4]= false;
                        if ((bytes[i]-bitInt[c+0]*128-bitInt[c+1]*64-bitInt[c+2]*32-bitInt[c+3]*16-bitInt[c+4]*8)/4==1)
                             bit[c+5]=true;
                        else
                             bit[c+5]= false;
                        if ((bytes[i]-bitInt[c+0]*128-bitInt[c+1]*64-bitInt[c+2]*32-bitInt[c+3]*16-bitInt[c+4]*8-bitInt[c+5]*4)/2==1)
                             bit[c+6]=true;
                        else
                             bit[c+6]= false;
                        if ((bytes[i]-bitInt[c+0]*128-bitInt[c+1]*64-bitInt[c+2]*32-bitInt[c+3]*16-bitInt[c+4]*8-bitInt[c+5]*4-bitInt[c+6]*2)==1)
                             bit[c+7]=true;
                        else
                             bit[c+7]= false;

    You can loop through and use a bitwise operator instead. Here is an example without the loop.
    byte b = 6 ;
    if( b & Math.pow( 2, 0 ) == Math.pow( 2, 0 ) ) ;
    // the 2^0 bit is on
    if( b & Math.pow( 2, 1 ) == Math.pow( 2, 1 ) ) ;
    // the 2^1 bit is onetc...
    You should get something like 110 when you're done.
    If you're wonder what & does (no, its not a boolean &&), it takes the bits in the two numbers you give it and returns a number with all the bits on that are on for each of them.
    For example:
    10011011 &
    11001101 =
    10001001
    So if we take
    110 (6) &
    010 (2^1, or 2) =
    010 (2 again)
    Which means that the number (6) has the 2^1 bit on.

  • Byte to bit and bit to byte conversion

    Hello,
    Does anyone know how to covert a byte into an array of booleans and vice versa? I think it has something to do with bitwise operations like >>.
    Thanks.

    If this right:
        public static byte bitsToByte(boolean[] bits)
              return bitsToByte(bits, 0);
        public static byte bitsToByte(boolean[] bits, int offset)
              int value = 0;
            for (int i = 0; i < 8; i++)
                   if(bits[i] == true)
                        value = value | (1 << i);
            return (byte)value;
         }

  • How to use SET BIT and GET BIT in ABAP Programming

    Hi,
    Our team is currently working for an Upgrade  project which is using a tool automatically upgrades when we supplly the code. fine, But now the requirement is , we need to write different test cases for the available key words in ABAP. Now we r looking for the usage of  " BIT ", keyword. so , kindly provide any program or code using this key word.
    Please find the description Provided and give some relative ABAP code to satisfy the given description.
    The data object byte_string must be byte-type. The statement reads the bit at the bit position BITPOS of the variable byte_string and assigns its value to the variable val. A default mode can be specified if required *
    Thanks & Regards,
    P.N.Kumar.

    What on earth are you testing? That ABAP still works? I think SAP might have run that through rigourous testing themselves.
    If you want sample code, why not read the ABAP help, and work some out for yourself?
    matt

  • Bytes and bits in Lookout

    This is for a Lookout 5.0 application. The OPC Client Object reads a integer value (between 0 and 32767 plus a sign bit) that represents a 16 bit word. What I want is knowing the integer value, unpack the word into 16 bits. How can I do this in Lookout?"

    I needed to do this and found a quick, mathematical way. Here it is:
    Lets say you have a 16 bit word with Bit#1 being the least significant bit- LSB- (farthest right) and Bit #16 being the most significant bit -MSB- (farthest left). As I am sure you know each bit has a decimal equivalent in value: Bit #1=1; Bit #2=2, Bit #3=4; Bit #4=8....Bit #15=16384, Bit#16=32768. The formual for a bit's value in decimal is (assuming the LSB satrts at 1 and not zero) 2^(Bit# - 1).
    So to parse a 16 bit word here is the formula to use in an expression:
    mod(int(Word/2^(Bit# - 1)),2) Ofcourse LSB bit# =1
    Since the 16th bit is a sign bit you only need to look at the word's sign:
    If(Word<0,1,0)
    Regards,
    Tommy Scharmann

  • Office 2013 & IE 64-bit: BAD combo to use with SPS (2010 & 2013)

    Few weeks ago I have installed Office 2013 in my office Win7.  Since then, whenever I click on a document in SPS 2010, it’s open TWICE!
    I was very annoyed because when I had Office 2010, I didn’t have this problem.
    After some search, I found that I’m not alone because some people have a similar problem with SPS 2013.
    After some intensive tests, I have found out the cause of the problem: IE 10 which is implicitly in
    64bit!
    Let me be clear, if I have the following combination, I have the “doubly open” problem:
    Win7 Pro 64bit + OS domain joined + Office 2013 64bit + IE 9 or 10 64bit
    If I have the following combination, I have NO such problem:
    Win7 Pro 64bit + OS domain joined + Office 2013 64bit + IE 9 32bit
    I have no idea if other combinations would lead or avoid my problem.  If anyone is interested to narrow down the combination, he’s welcome to do so :)
    The current solution is to downgrade IE 10 to IE 9 in order to have IE in  32bit.  There is no solution if one has to keep IE 10.  Hope this post of mine could help others in the same situation of me and hope Microsoft developers
    quickly fix the bug.

    Hi Horinius,
    Did you try to use IE 10 32-bit for this issue?
    In 64-bit Windows 7, Internet Explorer 10(IE 10) has 32-bit and 64-bit together in one browser now. If you turn on “Enhanced Protected Mode” , you will have 64-bit tabs by default for IE 10, and vice versa.
    For avoiding  your problem, you are able to enable 32-bit for IE 10.
    Here are some articles for you to take a look:
    http://www.sevenforums.com/tutorials/280434-internet-explorer-10-enable-32-bit-64-bit-ie10-windows-7-a.html
    http://www.ngohq.com/news/23295-how-to-enable-64-bit-internet-explorer-10-in-windows-7-a.html
    http://superuser.com/questions/561036/unable-to-open-ie-10-in-32-bit-mode
    I hope this helps.
    Thanks
    Wendy
    Wendy Li
    TechNet Community Support

  • I have two pc, one with windows 7 professional and another with windows 8.1. I'm the only owner and user of both. One works with 32 bits and the other (windows 8.1) , 64 bits. Can I use acrobat standard XI in both pc's being the only usuary?

    Just in case. I have two pc's one with windows 7 professional (32 bits) and another with windows 8.1 (64 bits). Can I use, with one license, as I'm the owner and only user, acrobat standard XI?. Thank you in advance
    Francisco

    Yes, the license allows 2 installs for the owner's personal use. You can check this in the license agreement if you wish.

  • How to find out if I am using a 32 bits or 64 bits version of JRE?

    How to find out if I am using a 32 bits or 64 bits version of JRE?
    If I have 2 instances of Java installed in 2 seperate directories, one 32 bits and other 64 bits on Linux. How do I identify which directory holds which version?
    Is there any command that can output this info?
    Regards,
    Billamama

    With a Sun JDK or JRE, you can use java -version:
    $ java -version
    java version "1.6.0"
    Java(TM) SE Runtime Environment (build 1.6.0-b105)
    Java HotSpot(TM) Server VM (build 1.6.0-b105, mixed mode)
    ... switch to the 64-bit JDK ...
    $ java -version
    java version "1.6.0"
    Java(TM) SE Runtime Environment (build 1.6.0-b105)
    Java HotSpot(TM) 64-Bit Server VM (build 1.6.0-b105, mixed mode)
    The last line says "64-Bit."

  • I have a Windows 7 Pro OEM disk that can install either the 32 or 64 bit version. When using version 5.0.3 of Bootcamp, I keep getting the message that it is a 32 bit disk.  Any ideas how to get it to recognize the 64 bit version?

    I have a Windows 7 Pro OEM disk that can install either the 32 bit or 64 bit versions.  When trying to setup a dual boot for my Mac Mini using Bootcamp version 5.0.3, I get the message that I have the 32 bit version of Windows.  Any ideas on how I can get it to recognize the 64 bit version so that I can partition my "Mini"?

    If by "OEM" you mean the disk came with another Win computer, it won't work. You need either a full retail verison or the "System Builders' Edition." I used the latter for my BC installation and it worked flawlessly and was marked as 64-bit--no mention of 32-bit.

  • Command used to know if Oracle is 64 bit or 32 bit in Unix

    What command would you use to tell if Oracle is 64 bit or 32 bit in Unix Systems.??
    What command would you use to tell if Solaris running on 64 bit or 32 bit.??
    Thnx
    Sravan

    probably file, I have no solaris here, but I tried on AIX
    $ file /app/oracle/product/*/bin/oracle
    /app/oracle/product/10.1.0.2/bin/oracle: 64-bit XCOFF executable or object module not stripped
    /app/oracle/product/10.1.0.3/bin/oracle: 64-bit XCOFF executable or object module not stripped
    /app/oracle/product/10.1.0.4/bin/oracle: 64-bit XCOFF executable or object module not stripped
    /app/oracle/product/8.1.7.4/bin/oracle: executable (RISC System/6000) or object module not stripped
    /app/oracle/product/9.2.0.5/bin/oracle: 64-bit XCOFF executable or object module not stripped
    /app/oracle/product/9.2.0.6/bin/oracle: 64-bit XCOFF executable or object module not stripped
    /app/oracle/product/9.2.0.7/bin/oracle: 64-bit XCOFF executable or object module not strippedas you can see, only the 8.1.7.4/bin/oracle kernel is not 64 bits, so it is 32 bits

  • Display brightness dims a bit/is 'fuzzy' when using expose (F9) ??

    Hi
    I realise that my Macbook Pro's brightness dims a bit after using the expose function. I know it'll dim a bit when you're using it but when i go back to the selected programme i'm running, it kinda of dims like a little (probably i'd say 1/2 or 1 notch) before reverting back to its normal brightness that i've set.
    So i'm asking is this normal?
    Additionally, i realise that my display tends to look a bit "fuzzy" when i use the expose. It's like one corner of the selected programme in expose would look fuzzy. A screenshot is shown as in the link:
    http://www.geocities.com/worldofdarkness89/MBPscreen.png
    Is this normal as well?? It's like i'm running my firefox and msn and when i use expose to alternate between these 2 windows, my msn chat at the corner, i realise the words turn out fuzzy and a tad distorted.
    This is my mac specs btws:
    Model: MacBookPro2,2, BootROM MBP22.00A5.B07, 2 processors, Intel Core 2 Duo, 2.16 GHz, 1 GB
    Graphics: ATI Radeon X1600, ATY,RadeonX1600, PCIe, 128 MB
    Memory Module: BANK 1/DIMM1, 1 GB, DDR2 SDRAM, 667 MHz
    AirPort: spairportwireless_card_type_airportextreme (0x168C, 0x87), 1.2.2
    Bluetooth: Version 1.9.5f4, 2 service, 0 devices, 1 incoming serial ports
    Network Service: AirPort, AirPort, en1
    Serial ATA Device: Hitachi HTS541612J9SA00, 111.79 GB
    Parallel ATA Device: MATSHITADVD-R UJ-857D
    USB Device: Built-in iSight, Micron, Up to 480 Mb/sec, 500 mA
    USB Device: PS/2+USB Mouse, Up to 1.5 Mb/sec, 500 mA
    USB Device: Apple Internal Keyboard / Trackpad, Apple Computer, Up to 12 Mb/sec, 500 mA
    USB Device: IR Receiver, Apple Computer, Inc., Up to 12 Mb/sec, 500 mA
    USB Device: Bluetooth USB Host Controller, Apple, Inc., Up to 12 Mb/sec, 500 mA
    I hope to get some answers. Thanks!

    Hello and Welcome to Apple Discussions. 
    Have you tried Zapping the PRAM?
    The PRAM holds various settings such as display settings.
    regards
    mrtotes

Maybe you are looking for

  • Moving music from old PC to new Macbook

    Just got a new home PC, so all my music was deleted from it. I also just got a new MacBook. All my music is on my ipod, is there anyway I can transfer the music from my ipod to my mac, bearing in mind it is formatted for a PC?

  • Best practices for cleaning up after a Bulk REST API v2 export

    I want to make sure that I am cleaning up after my exports (not leaving anything staging, etc). So far I am DELETEing $ENTITY/exports/$ID and $ENTITY/exports/$ID/data as described in the Bulk REST API documentation Using a dataRetentionDuration when

  • Several Minor Issues

    Here are several issues that I have noted since my install last week: *ACTIVITY MONITOR: Wouldn't load, kept indicating that it had "quit unexpectedly" and wouldn't relaunch, reset or ignore. *SPACES: I'm using six spaces. I had a lot of trouble gett

  • When I have Safari maximized, can I lock the menu bar?

    Viewing Safari from my desktop, I do and can view/use the menu bar. But, what about when I have Safari maximized? It is always in hiding. Is there a way to lock it? I would like to know time and battery status at a glance....

  • Loss of sound on ring / text alert

    My iPhone 4 appears to be stuck on mute. I've re-set the phone and and can hear the ring in settings but there is no sound when i receive a call or text. Help much appreciated. Thanks, Peter