Bitwise Shift Clarification / Bug ?

Java Tutorial: Shift & Logical Operators...
has no example to clarify difference between op1 >> op2 vs op1 >>> op2 (only says latter is unsigned).
To help understand, I wrote following code...
public class BitwiseDemo {
public static void main(String[] args) {
int op1 = -13;
int op2 = 2;
int res1 = ( op1 >> op2 );
int res2 = ( op1 >>> op2 );
System.out.println("op1 >> op2 " + res1 );
System.out.println("op1 >>> op2 " + res2 );
I got result...
op1 >> op2 -4
op1 >>> op2 1073741820 .... (big)
In 2's complement arithmetic which Java uses...
-13 =1111 1111 1111 1111 1111 1111 1111 0011
If we shift -13 to right by two retaining sign bit
AND padding with 1 (not 0)...
-4 =1111 1111 1111 1111 1111 1111 1111 1100
If we shift -13 to right by two including sign bit
AND padding with 0 (as doco says)...
(big)=0011 1111 1111 1111 1111 1111 1111 1100
I suggest doco should read...
pad with leading sign bit
pad with zero
Q:Is the above correct ?
Q:Is there a part of Java doco which gives an example
of this? I don't think it makes a difference for positive
numbers.
Q:Do I get some award for this great piece of learning?
Instead of using class int, I use class byte but does not compile...
BitwiseDemo.java:10 (&11): possible loss of precision
found : int
required : byte
byte res1 = ( op1 >> op2 );
^
I expected it to compile and have the answers...
In 2's complement arithmetic which Java uses...
-13 =1111 0011
If we shift -13 to right by two retaining sign bit
AND padding with 1...
-4 =1111 1100 (>>)
If we shift -13 to right by two including sign bit...
60 =0011 1100 (>>>)
I also get no compile with class short.
Instead of using class int, I use class long...
I get -4 and 46116860184273877900
Q: Does this mean that the >> and >>> operators use class int as a minimum? Is this in doco?
Rgds
Tony

The program I used was...
public class BitDemo {
public static void main(String[] args) {
byte b= (byte)0x80;
byte c= (byte)0x80;
b >>>= 1;
c >>= 1;
System.out.println("b >>>= 1 " + b );
System.out.println("b >>= 1 " + c );
This produced -64 in both cases as you said.
PS I used (byte) to type cast the 0x80 assignment.
I also used byte b= -128; which did the same thing.
My logic says...
0x80 =1000 0000
= =1100 0000 (-64)
= =0100 0000 (+64)
So my maths doesn't agree ! The sign is wrong.
Then I tried the program with int instead of byte...
public class BitDemo {
public static void main(String[] args) {
int b= 0x80000000;
int c= 0x80000000;
b >>>= 1;
c >>= 1;
System.out.println("b >>>= 1 " + b );
System.out.println("b >>= 1 " + c );
Result...
b >>>=1 1073741824
b >>=1 -1073741824
So using int I get different signs which agrees with my maths. I assume the issue is due to changing from byte to int then to byte again. Next experiment...
public class BitDemo {
public static void main(String[] args) {
byte bb;
byte bc;
int b= 0x80000000;
int c= 0x80000000;
b >>>= 1;
c >>= 1;
bb=(byte)b;
bc=(byte)c;
System.out.println("b >>>= 1 " + bb );
System.out.println("b >>= 1 " + bc );
So in above all maths is int with a final conversion to byte. This gives me zero in both cases.
Signed: Failed final exam and confused.

Similar Messages

  • The Great Shift-Space bug in OBIEE

    Very interesting OBIEE (Oracle Business Intelligence Enterprise Edition) Bug. This might happen to you may be one out of 1,000,000.
    Read full from http://musnet.blogspot.com/2010/05/great-shift-space-bug-in-obiee-very.html
    Regards
    Musnet

    Paul wrote:
    It sounds like a bug I've come across before. Check article 1054338.1 from support.oracle.com. It contains the reason for this error and details of a workaround. You will need to upgrade OC4J to 10.1.3.5.
    Paul
    http://total-bi.com
    Thanks

  • The Great Shift-Space bug in OBIEE  (Second Post)

    I have posted this before but no one was answered the following issue. Please respond.
    Very interesting OBIEE (Oracle Business Intelligence Enterprise Edition) Bug. This might happen to you may be one out of 1,000,000.
    Read full from http://musnet.blogspot.com/2010/05/great-shift-space-bug-in-obiee-very.html
    Regards
    Musnet

    Hi Subhasish,
    Thanks for the reply, glad that its something that is reproducible!
    Do you have any idea of timescale? Or is it likely that I will have to modify the registry as above to get this working?
    If I am going to have to modify the registry, please can you let me know if the resolution I have tested above is safe and viable? Or are there other settings that I will need to change to make the cluster fully aware of the proper path to the CSVs for its
    VMs?
    Also, is there a known procedure for renaming the reparse point whilst VMs are running on it? This would allow me to negate the issue before copying the roles to the new cluster :-)
    Thanks again,
    Tom

  • Bitwise shift in ABAP?

    Hi all,
    How can I shif data bitwise in SAP? Is it possible?
    Best Regards
    Marcin Cholewczuk

    Hi,
    Perhaps the below link could give ideas:
    http://stackoverflow.com/questions/8349886/bit-shifts-with-abap
    PS: I am not familiar with ABAP coding, as mainly into Basis - just thought could help
    Regards,
    Srikishan

  • Xorg - SHIFT key bugs out randomly after TV-hardware is connected

    I'm on Xfce4. When I hold down left SHIFT key and press some other keys, after a while the SHIFT key may "unregister" itself. What I mean is, it stops working as if I had released it, although I'm still pressing it down. Ie I'm suddenly writing lower-case again and stuff. This behaviour is application-independant apparently.
    I tried running 'showkey' and it correctly reported pressing+releasing of the SHIFT key (keycode 42) when I actually physically pressed and released it. It did NOT report release of the SHIFT key when it in fact stopped working. So it doesn't seem to be a keyboard hardware problem or something.
    The right SHIFT key (showkey says keycore 54 for this one) seems to work correctly though (but it's not really a comfortable work-around..).
    Is there maybe a trick that could be used as a workaround, to somehow switch the right and left shiftkey's key codes? Maybe that could "fix" it. >:)
    I had a look at xmodmap, but that shows entirely different "keycodes" for SHIFT keys so I'm a bit stumped:
    $ xmodmap -pk
    ..for "keycode 42" it had this line:
    42 0x0067 (g) 0x0047 (G) 0x0067 (g) 0x0047 (G) 0x03bf (eng) 0x03bd (ENG) 0x03bf (eng) 0x03bd (ENG)
    ..and for left shift key it had "50" in the "keycode" column:
    50 0xffe1 (Shift_L) 0x0000 (NoSymbol) 0xffe1 (Shift_L) 0x0000 (NoSymbol) 0xffe1 (Shift_L)
    Anyway, I tried out https://wiki.archlinux.org/index.php/Xmodmap:
    xmodmap -pke > ~/.Xmodmap
    ..then edited that file and changed the Shift_L (50) and Shift_R (62) lines, and did
    xmodmap ~/.Xmodmap
    ..and my X froze up completely, not even registering mouse clicks, might wanna correct the Wiki there^^.
    After a reboot, my xmodmap -pke showed the two lines swapped as intended though - but 'showkey' still shows keycode 42 for left and 54 for right, so swapping didn't work here.
    Funny thing is, now after a fresh reboot I seem unable to reproduce the bug, so I'll wait and see what happens I guess.
    Now I have read about people getting a bug where SHIFT key is suddenly _pressed_ on its own, unlike my prob where it is released, and those people always write that it happens when a TV card is connected, and that it is detected as "keyboard" according to X0.log.
    So I just connected my usual bunch of USB stuff that I had disconnected earlier just while that reboot happened after which my problem didn't surface.
    My X0.log:
    [ 647.676] (II) config/udev: Adding input device UVC Camera (eb1a:2571) (/dev/input/event13)
    [ 647.676] (**) UVC Camera (eb1a:2571): Applying InputClass "evdev keyboard catchall"
    [ 647.676] (II) Using input driver 'evdev' for 'UVC Camera (eb1a:2571)'
    [ 647.676] (**) UVC Camera (eb1a:2571): always reports core events
    [ 647.676] (**) evdev: UVC Camera (eb1a:2571): Device: "/dev/input/event13"
    [ 647.676] (--) evdev: UVC Camera (eb1a:2571): Vendor 0xeb1a Product 0x2571
    [ 647.677] (--) evdev: UVC Camera (eb1a:2571): Found keys
    [ 647.677] (II) evdev: UVC Camera (eb1a:2571): Configuring as keyboard
    [ 647.677] (**) Option "config_info" "udev:/sys/devices/pci0000:00/0000:00:1d.7/usb1/1-5/1-5.1/1-5.1:1.0/input/input13/event13"
    [ 647.677] (II) XINPUT: Adding extended input device "UVC Camera (eb1a:2571)" (type: KEYBOARD, id 14)
    [ 647.677] (**) Option "xkb_rules" "evdev"
    [ 647.677] (**) Option "xkb_model" "evdev"
    [ 647.677] (**) Option "xkb_layout" "de"
    [ 654.995] (II) config/udev: Adding input device Arduino LLC Arduino Leonardo (/dev/input/event14)
    [ 654.995] (**) Arduino LLC Arduino Leonardo: Applying InputClass "evdev pointer catchall"
    [ 654.995] (**) Arduino LLC Arduino Leonardo: Applying InputClass "evdev keyboard catchall"
    [ 654.995] (II) Using input driver 'evdev' for 'Arduino LLC Arduino Leonardo'
    [ 654.995] (**) Arduino LLC Arduino Leonardo: always reports core events
    [ 654.995] (**) evdev: Arduino LLC Arduino Leonardo: Device: "/dev/input/event14"
    [ 654.996] (--) evdev: Arduino LLC Arduino Leonardo: Vendor 0x2341 Product 0x8036
    [ 654.996] (--) evdev: Arduino LLC Arduino Leonardo: Found 3 mouse buttons
    [ 654.996] (--) evdev: Arduino LLC Arduino Leonardo: Found scroll wheel(s)
    [ 654.996] (--) evdev: Arduino LLC Arduino Leonardo: Found relative axes
    [ 654.996] (--) evdev: Arduino LLC Arduino Leonardo: Found x and y relative axes
    [ 654.996] (--) evdev: Arduino LLC Arduino Leonardo: Found keys
    [ 654.996] (II) evdev: Arduino LLC Arduino Leonardo: Configuring as mouse
    [ 654.996] (II) evdev: Arduino LLC Arduino Leonardo: Configuring as keyboard
    [ 654.996] (II) evdev: Arduino LLC Arduino Leonardo: Adding scrollwheel support
    [ 654.996] (**) evdev: Arduino LLC Arduino Leonardo: YAxisMapping: buttons 4 and 5
    [ 654.996] (**) evdev: Arduino LLC Arduino Leonardo: EmulateWheelButton: 4, EmulateWheelInertia: 10, EmulateWheelTimeout: 200
    [ 654.996] (**) Option "config_info" "udev:/sys/devices/pci0000:00/0000:00:1d.7/usb1/1-5/1-5.4/1-5.4:1.2/input/input14/event14"
    [ 654.996] (II) XINPUT: Adding extended input device "Arduino LLC Arduino Leonardo" (type: KEYBOARD, id 15)
    [ 654.996] (**) Option "xkb_rules" "evdev"
    [ 654.996] (**) Option "xkb_model" "evdev"
    [ 654.996] (**) Option "xkb_layout" "de"
    [ 654.998] (II) evdev: Arduino LLC Arduino Leonardo: initialized for relative axes.
    [ 655.001] (**) Arduino LLC Arduino Leonardo: (accel) keeping acceleration scheme 1
    [ 655.001] (**) Arduino LLC Arduino Leonardo: (accel) acceleration profile 0
    [ 655.001] (**) Arduino LLC Arduino Leonardo: (accel) acceleration factor: 2.000
    [ 655.001] (**) Arduino LLC Arduino Leonardo: (accel) acceleration threshold: 4
    [ 655.005] (II) config/udev: Adding input device Arduino LLC Arduino Leonardo (/dev/input/mouse3)
    [ 655.005] (II) No input driver specified, ignoring this device.
    [ 655.005] (II) This device may have been added with another device file.
    Now I'm wondering, my webcam gets detected as "keyboard" (id 14) ^^' well and so does my Arduino, but that's natural for Leonardo models.
    I started up the webcam, so the uvc modules are now loaded, but still I'm now unable to reproduce the bug for some reason. With either SHIFT key. Well that's good sort of, but then again, not so good to track what causes it when it happens And why does X think that webcams and tv  cards are keyboards?
    Will post again when the bug surfaces again I guess.
    Ok, after plugging in a usb-tv box, the bug started happening again, except this time it's the rigth shift key that doesnt work correctly, while the left shift key seems fine.
    So it seems the xmodmap change worked, although showkey still shows 42 for left and 54 for right.
    This might do as a workaround for now, although someone should figure out why tv cards (and tv usb boxes in my case) mess up the shift key in Xorg.
    Apparently the IR-receiver part of my tv-box was recognized as "keyboard":
    [ 17549.633] (II) config/udev: Adding input device IR-receiver inside an USB DVB receiver (/dev/input/event15)
    [ 17549.633] (**) IR-receiver inside an USB DVB receiver: Applying InputClass "evdev keyboard catchall"
    [ 17549.633] (II) Using input driver 'evdev' for 'IR-receiver inside an USB DVB receiver'
    [ 17549.634] (**) IR-receiver inside an USB DVB receiver: always reports core events
    [ 17549.634] (**) evdev: IR-receiver inside an USB DVB receiver: Device: "/dev/input/event15"
    [ 17549.634] (--) evdev: IR-receiver inside an USB DVB receiver: Vendor 0xccd Product 0x38
    [ 17549.634] (--) evdev: IR-receiver inside an USB DVB receiver: Found keys
    [ 17549.634] (II) evdev: IR-receiver inside an USB DVB receiver: Configuring as keyboard
    [ 17549.634] (**) Option "config_info" "udev:/sys/devices/pci0000:00/0000:00:1d.7/usb1/1-1/input/input15/event15"
    [ 17549.634] (II) XINPUT: Adding extended input device "IR-receiver inside an USB DVB receiver" (type: KEYBOARD, id 16)
    [ 17549.634] (**) Option "xkb_rules" "evdev"
    [ 17549.634] (**) Option "xkb_model" "evdev"
    [ 17549.635] (**) Option "xkb_layout" "de"
    Can I somehow find out which modules were loaded when I plugged it in so I can unload those?
    Also, I tried
    $ lsmod |grep dvb
    dvb_usb_cinergyT2 6645 2147483647
    dvb_usb 15171 1 dvb_usb_cinergyT2
    dvb_core 79241 1 dvb_usb
    rc_core 11081 1 dvb_usb
    usbcore 126764 7 uhci_hcd,uvcvideo,dvb_usb,ehci_hcd,dvb_usb_cinergyT2,usbhid,cdc_acm
    i2c_core 16944 7 drm,i915,i2c_i801,dvb_usb,drm_kms_helper,i2c_algo_bit,videodev
    $ rmmod dvb_usb_cinergyT2
    rmmod: ERROR: Module dvb_usb_cinergyT2 is in use
    but I don't have any media player running anymore, so why is the module in use and how do I see by what it is in use? Forced removal via rmmod -f worked by the way. Then I was able to remove the other two dvb_usb_ modules, and usbcore and i2c_core disappeared automatically.. but the bug still occurs! Any way to find out which other modules were possibly loaded, or what was done by the system, when I plugged in the tv box?
    Last edited by Jindur (2013-01-06 05:08:51)

    Do you have the 3 year Applecare? If so, you could try calling Applecare and see if they can help you resolve this over the phone. If not, be sure to get this problem documented with a case number before your 1 year warranty is up. If this has just been a constant hassle, you could ask to talk to Customer Relations.
    It sounds like you may have some hardware problems with the keyboard and the trackpad, which could be causing at least some of the problems. Any chance of getting to an Apple store to have it looked at, or would you have to send it in?
    Good luck!

  • Bitwise shift operator...

    I know this is very basic but I've never done this...
    If I have an object that is an Integer, and I want to increase it by 1, isn't this how you do it?
    Object ob=new Integer(10);
    ob=ob>>1;it tells me that >> operator cannot be applied to object, int
    So what can it be applied to..?

    Ummmm,sadly, no... :(
    I really do lack basic computer skills, I don't know
    a lot about binary and stuff... but how would you do
    what I want to do..?I asked because it's quite a weird code. Just checking.
    OK, so:
    the binary shift operator can only be applied between to ints, that is primitives, no Objects (like Integer is).
    This operator is not used to increase a number, but to shift its bits by one to the right.
    Usage:
    int i,j;
    j = 10;
    i = j >> 1;
    Integer obj = new Integer(10);
    int res = obj.intValue() >> 1;
    Integer resObj = new Integer(res);

  • Shift constrain bug!

    Shift constrain when scaling or creating objects doesn't work!!! This is issue is crippling. the official solution is to throw out the adobe preferences before you start of illustrator. unfortunately I need to do that every time since it just happens again. and sometimes this doesn't solve the problem. it looks like this problem has been around since CS3. this pretty much renders illustrator useless.
    my feature request is to fix this problem!
    Running CS4 on windows 7 64 bit....

    There are already mouse listeners in the call stack before this method.
    These mouse listeners DO have the shift modifier present.
    The problem is when translating the mouse listener event to a button pressed action the modifiers are thrown away by avoiding the constructor with modifiers.
    I don't see a way around overriding this method. However, I'm all ears.
    Fiskes

  • What does these bitwise shift doing here ??

    Hello Everybody,
    I was trying some code given n net for reading BMP file and saving into another format and not able to understand the following code which is converting int into Dword. My Int value is 64 which I am trying to convert.:-
    code:
    * intToDWord converts an int to a double word, where the return
    * value is stored in a 4-byte array.
    private byte [] intToDWord (int parValue)
    byte retValue [] = new byte [4];
    retValue [0] = (byte) (parValue & 0x00FF);
    retValue [1] = (byte) ((parValue >> 8) & 0x000000FF);
    retValue [2] = (byte) ((parValue >> 16) & 0x000000FF);
    retValue [3] = (byte) ((parValue >> 24) & 0x000000FF);
    return (retValue);
    I would like to request if someone can spare a moment and explain me following:-
    1. Why I need to use >> ?
    2. How one can decide how much shift is needed and in which direcion?
    3. Why there is a need of using & operator ?
    4. How one can decide with which it should be done as it is done with 0x000000FF for 2,3 and 4 th element.
    I would be highly obliged if some one can help me to understand the above.
    regrds,
    arun

    well first this thing is simply taking your integer value you passed in and cutting it up into little byte size pieces.
    For an explanation you ahve to think about indiviual bits. A byte consists of 8 bits
    and an int is 4 bytes in Java (as in many languages). Now what this code does is it takes 8 bit chunks and stores them in a different position in the array.
    retVal[0] = the lowest order 8 bits. It ands the integer with 0x0ff or ...011111111
    retVal[1] = the next 8 bits by shifting out the first 8 bits then it ands this with
    ...011111111. This anding is important because it maintains only the lowest 8 bits of the integer. If the method decided to and the integer with 011111100 then the lowest two bits would always be lost (set to zero). Its simply a matter of boolean algebra.
    Anyway, you just continually shift 8 bits at a time in order to get the 8 bit chunk that is necessary to store into the array slot.

  • [LAVA Cross Post] CTRL+SHIFT+Alpha Shortcuts don't work in LabVIEW

    Cross-post from LAVA: http://lavag.org/topic/15619-ctrlshift-shortcuts-sometimes-not-working-in-labview/
    Bug Synopsis: CTRL+SHIFT+Alpha shortcuts do not work in LabVIEW. Most notably, CTRL+SHIFT+Z, CTRL+SHIFT+E, and CTRL+SHIFT+S
    Test setup: LV2012 32bit with f1 patch running in Win7 64bit inside a Parallels 8 VM in OS X 10.8.1
    To summarize the testing I have tried:
    Many different LabVIEW, Guest OS, and Host OS combinations all fail, including:
    LV2012f1 32 and 64 bit, and LV2009 32 bit
    Win7 32 and 64bit, and also WinXP x64
    Parallels 7 and Parallels 8
    OS X 10.7 and 10.8
    Capturing the keyboard by the VM
    Twiddling every keyboard setting possible on Parallels, Guest, and Host
    Reinstalling keyboard drivers
    Plugging in a known-good keyboard that works on a native Windows machine
    Deleting LabVIEW.ini and letting it regenerate
    Remapping the shortcuts from, e.g., CTRL+SHIFT+E to CTRL+E - in this case, "Show in Project" works, so this might indicate it's a problem registering the shortcut press, not invoking the action itself.
    Sending the keystrokes via on-screen keyboards from both Guest and Host
    Sending the keystrokes via SendInput from user32.dll WinAPI
    Testing every imaginable combo of FN, CONTROL, ALT/OPTION, COMMAND/CMD, SHIFT
    Reinstalling VMs from scratch and reinstalling LV
    Here's a kicker: CTRL+SHIFT+Alpha shortcuts work fine on other Windows programs (I've tried 4 different programs, including Chrome, Notepad++, Paint.NET), yet it does NOT work for VIPM with CTRL+SHIFT+C. This means that the only two programs where the CTRL+SHIFT+Alpha bugs exist are both LabVIEW-related.
    Here's another kicker: It's only CTRL+SHIFT+Alpha shortcuts with the prob - CTRL+SHIFT+3 properly toggles grid alignment, and the "Tools >> Options >> Menu shortcuts" will register any CTRL+SHIFT+Non-alpha shortcut; it just does not respond to the CTRL+SHIFT+Alpha shortcuts.
    Any new troubleshooting ideas are highly appreciated; please feel free to jump in here or on LAVA.
    a.lia-user-name-link[href="/t5/user/viewprofilepage/user-id/88938"] {color: black;} a.lia-user-name-link[href="/t5/user/viewprofilepage/user-id/88938"]:after {content: '';} .jrd-sig {height: 80px; overflow: visible;} .jrd-sig-deploy {float:left; opacity:0.2;} .jrd-sig-img {float:right; opacity:0.2;} .jrd-sig-img:hover {opacity:0.8;} .jrd-sig-deploy:hover {opacity:0.8;}
    Solved!
    Go to Solution.

    X. wrote:
    Still well and alive in Parallels 9 and LabVIEW 2013 SP1. Of course I could upgrade to the latest versions to check whether things have gotten any better.
    Any news on that?
    @mellroth figured out the solution :-)
    a.lia-user-name-link[href="/t5/user/viewprofilepage/user-id/88938"] {color: black;} a.lia-user-name-link[href="/t5/user/viewprofilepage/user-id/88938"]:after {content: '';} .jrd-sig {height: 80px; overflow: visible;} .jrd-sig-deploy {float:left; opacity:0.2;} .jrd-sig-img {float:right; opacity:0.2;} .jrd-sig-img:hover {opacity:0.8;} .jrd-sig-deploy:hover {opacity:0.8;}

  • 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

  • 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

  • Fast Inverse Square Root

    I expect no replies to this thread - because there are no
    answers, but I want to raise awareness of a faculty of other
    languages that is missing in Flash that would really help 3D and
    games to be built in Flash.
    Below is an optimisation of the Quake 3 inverse square root
    hack. What does it do? Well in games and 3D we use a lot of vector
    math and that involves calculating normals. To calculate a normal
    you divide a vector's parameters by it's length, the length you
    obtain by pythagoras theorem. But of course division is slow - if
    only there was a way we could get 1.0/Math.sqrt so we could just
    multiply the vector and speed it up.
    Which is what the code below does in Java / Processing. It
    runs at the same speed as Math.sqrt, but for not having to divide,
    that's still a massive speed increase.
    But we can't do this in Flash because there isn't a way to
    convert a Number/float into its integer-bits representation. Please
    could everyone whinge at Adobe about this and give us access to a
    very powerful tool. Even the guys working on Papervision are having
    trouble with this issue.

    that's just an implementation of newton's method for finding
    the zeros of a differentiable function. for a given x whose inverse
    sq rt you want to find, the function is:
    f(y) = 1/(y*y) - x;
    1. you can find the positive zero of f using newton's method.
    2. you only need to consider values of x between 1 and 10
    because you can rewrite x = 10^^E * m, where 1<=m<10.
    3. the inverseRt(x) = 10^^(-E/2) * inverseRt(m)
    4. you don't have to divide E by 2. you can use bitwise shift
    to the right by 1.
    5. you don't have to multiply 10^^(-E/2) by inverseRt(m): you
    can use a decimal shift of inverseRt(m);
    6. your left to find the positive zero of f(y) = 1/(y*y) - m,
    1<=m<10.
    and at this point i realized what, i believe, is a much
    faster way to find inverse roots: use a look-up table.
    you only need a table of inverse roots for numbers m,
    1<m<=10.
    for a given x = 10^^E*m = 10^^(e/2) *10^^(E-e/2)*m, where e
    is the largest even integer less than or equal to E (if E is
    positive, e is the greatest even integer less than or equal to E,
    if E is negative), you need to look-up, at most, two inverse roots,
    perform one multiplication and one decimal shift:
    inverseRt(x) = 10^^(-e) * inverseRt(10) *inverseRt(m), if
    E-e/2 = 1 and
    inverseRt(x) = 10^^(-e) * inverseRt(m), if E-e/2 = 0.

  • Reading grayscale values from saved image

    Hi,
    I've written several methods that crop, convert to grayscale, histogram equalise and then resize a colour jpeg image for preparing sets of images for a face detection neural network. The next thing I want to do is to write a method that allows me to read that saved grayscale images pixel values back as singular grayscale values from the RGB values that were used to save the jpeg. I used this code to create the 2D array of grayscale pixel values
          for (int i = 0; i < imageWidth; i++)
                for (int j=0; j <imageHeight; j++)
                    grayRGB[i][j] = (rgb[i][j] & 0xff000000) | (eqGray[i][j]<<16) | (eqGray[i][j]<<8) | (eqGray[i][j]);
                    img.setRGB(i, j, grayRGB[i][j]);
                }and then used this code to resize the image:
            BufferedImage resized = new BufferedImage(20,20,1);
            Graphics2D g = resized.createGraphics();
            g.drawImage(img, 0, 0, 20, 20, null);
            g.dispose();my class gets the RGB values on instantiation as follows:
            //get RGB pixel values for image loaded
            for (int i = 0; i < imageWidth; i++)
                for (int j=0; j <imageHeight; j++)
                    rgb[i][j]= inputImage.getRGB(i,j);
                    //perform bitwise shift rgb information values to obtain appropriate values for each colour pixel
                    r[i][j]=  (rgb[i][j] >> 16) &0xff;
                    g[i][j]=  (rgb[i][j] >> 8) &0xff;
                    b[i][j]=  (rgb[i][j]) &0xff;
                }Is there a way to get the grayscale values directly from an image that is already converted to grayscale without having to perform the grayscale conversion method again, perhaps using a similar bitwise shift?
    Thanks
    Nick

    answering this myself for those lost souls like i was a while ago:
    the answer is very simple when you get to know it :) : use a signed type for your image. this can be achieved by using the Format Operator (javax.media.jai.operator.FormatDescriptor). an example as follows :
            BufferedImage bufferedImage= someimage...
            ParameterBlock pb = new ParameterBlock();
            pb.addSource(bufferedImage);
            pb.add(DataBuffer.TYPE_SHORT);
            RenderedImage formattedImage =
                    JAI.create("format", pb, null);
    // you may use as well TYPE_DOUBLE or TYPE_FLOATimage could be of any type such as PlanarImage, BufferedImage, RenderedImage etc..
    then all you need to do is read your pixel values by using an iterator such as RectIter or RandomIter to access pixel values etc..
    San

  • File Dialog Box often takes a long time to execute

    Hi all
    The Labview File Dialog Box Express VI sometimes takes 5 to 10 seconds to execute. On other occasions, it executes in a blink of an eye. Why is that so?
    I have tried to use the older Open/Create/Replace File VI as suggested in one of the forum's posts...but it behaves exactly the same way. Another problem is the trimming of the filename, which has also been reported and has NOT YET been solved.
    (By the way...Recently, I updated to LV 2012 SP2 by suggestion of the NI Update Manager, only to find out that I was not entitled to this SP (which apparently only includes bug fixes) and I will have to roll back to LV 2012. Still,  in the evaluation version I can see that the bug is not fixed. Labview must have a lot of serious bugs for NI to ask for a paid bug fix, in which some bugs remain after having been reported a long time ago..well...)
    What worries me now is that intermittent lag in the execution of the File Dialog (such a basic basic function of a program...). Anyone have any idea about this? The support menu said "Ask an engineer"...any of the NI engineers has any suggestion?
    Regards
    Helder
    Attachments:
    FileDialogTest.vi ‏26 KB

    First of all: Thank you very much for the objective answer. I suppose that yor actually ARE a NI engineer, as I had hoped for.
    lease find my comments above (helder---------------------)
    helder wrote:
    The Labview File Dialog Box Express VI sometimes takes 5 to 10 seconds to execute. On other occasions, it executes in a blink of an eye. Why is that so?
    What worries me now is that intermittent lag in the execution of the File Dialog (such a basic basic function of a program...). Anyone have any idea about this?
    The file dialog is provided by the OS, so if it is slow it is not LabVIEW's fault.
    What kind of computer do you have? Is this a laptop that spins down the HD to save power? In this case it needs to wait for the HD to spin up. (You can change the windows power profile or you can spend more money and get an SSD).
    Are you very low on memory?
    Does your LabVIEW program waste 100% CPU in parallel doing nothing due to bad coding?
    Are you pointing to a location that has millions of files?
    Are you pointing to a network location?
    helder:---------------------------------------
    I understand that the File Dialog is provided by the OS. But I have other applications on my PC and this doesn't happen - just in Labview. Sorry! And sometimes it
    doesn't happen. Every 10 times I open the File dialog Box, 5 times it takes long and 5 times it is immediate.
    (I am not low on memory, my coding is not bad>-look at the VI I sent, it just contains the fragment which uses the File Dialog Box and it behaves the same way! I am pointing to the same location that the other applications point to, I am not pointing to a network location, the PC is not spinning the disk down, etc etc.)
    But yes, I will try it on another PC
    (There was another post on the forum on this issue, but can't seem to find it now, just find my own post )
    I attach a video demo of what happens.
    helder wrote:
    Another problem is the trimming of the filename, which has also been reported and has NOT YET been solved.
    What problem is that? Can you elaborate? There is a known bug in the windows dialog box that sometimes the pre-filled file names are shifted and not fully visible. This is a windows bug documented by Microsoft and LabVIEW has no control over it. It is not NIs job to fix OS problems.
    helder:-------------------------------------------
    Of course you can't fix the OS.
    If it is a windows bug, we will have to live with it.
    A previous post on your forum did not provide me with that information (http://forums.ni.com/t5/LabVIEW/File-dialog-trimmi​ng-the-default-name/td-p/2189874). The fact that it is a windows bug was not mentioned there. 
    helder wrote:
    Hi all
    (By the way...Recently, I updated to LV 2012 SP2 by suggestion of the NI Update Manager, only to find out that I was not entitled to this SP (which apparently only includes bug fixes) and I will have to roll back to LV 2012. Still,  in the evaluation version I can see that the bug is not fixed.
    Patches are included, service packs are not included. I think this is well documented. Most users are on SSP, this way you are always entitled to the newest version.
    As with anything else, software has bugs. It is impossible to test a huge, complex system like LabVIEW under all scenarios. The possible number of combinations of hardware and other installed software on any particular computer probably exceeds the number of atoms in the universe. It is actually amazing how few bugs there are and how well it works. What "bug" are you talking about? Bugs are prioritized according to rules. Critical bugs are typically fixed very quickly. A cosmetic issue that only affects you and nobody else will take longer or might not even get fixed. Are you talking about a confirmed bug that could be reproduced by NI? Do you have a CAR#?
    helder:----------------------------------------
    I was referring to the file-name-shifting-cosmetic-bug that the October-2012 post had indicated. But if it is a Windows-bug, NI does not have any responsibility, of
    course.
    Regarding the bugs, of course they are unavoidable.
    helder wrote:
    Labview must have a lot of serious bugs for NI to ask for a paid bug fix, in which some bugs remain after having been reported a long time ago..well...)
    That sentence makes no sense! Why would the number of serious bugs depend on the cost of upgrading?? You are just rambling here....
    In an ideal world, NI would have an unlimited number of programmers that can work 24/7 to immediately fix any discovered bug. This would only be possible if all users are willing to pay an unlimited amount of money for the software. As I mentioned, bug fixes are free in the form of patches, and they come out regularly. Service packs include new features and are not free.
    helder:---------------------------------------
    "....include new features"..????
    ---->>From http://www.ni.com/labview/release-details/
    "LabVIEW 2012 Service Pack 1 is an exclusive update to LabVIEW 2012 for NI Standard Service Program (SSP) customers. There are no new product features introduced in service pack releases; instead, these releases provide bug fixes and improved stability for LabVIEW 2012. For a list of these bug fixes, click here."
    No new features, just bug fixes!"
    Moreover: If it isn't free, it shouldn' have let me update if I am not a SSP costumer.
    Now I have a 45 days evaluation version. After that, I have to uninstall and reinstall everything.That takes some time and effort.
    If there is a more direct way of rolling back t the previous version, please let me know.
    Thank you

  • Photoshop 12.0.4 is out (Tue 3 May) - what's new?

    Looks like Photoshop 12.0.4 was released this morning, somewhere around 2am Eastern.
    Are there full release notes somewhere? (Like InDesign has here for 7.0.4.)
    The above URL notes some changes:
    The 12.0.4 update enables specially designed apps on tablets,
    smartphones, and PCs to communicate with and control interaction with
    Photoshop CS5 (Located in the File menu: Remote Connections). Now you
    can be creative on other devices and instantly incorporate what you
    create into Photoshop. You must install the 12.0.4 update to activate a
    remote connection between Photoshop CS5 and any apps that Adobe or
    third-party developers create to interact with Photoshop. For example,
    Photoshop CS5 must be updated to 12.0.4 to interact with three new iPad
    apps that Adobe has designed to work with it - Adobe Nav, Adobe Color
    Lava, and Adobe Eazel. Available on the App Store.
    The 12.0.4 update also fixes liquify performance, type related
    crashes, and other top customer issues. The most significant fixes
    include the following:
    • A number of potential security vulnerabilities have been addressed.
    • Liquify save mesh now works as expected.
    • An issue with Sharpen crashing has been fixed.
    • An issue with Quick Selection crashing has been fixed.
    • The Orphea Studio File Info issue has been resolved.
    One might also infer that bugs fixed in the Windows-only 12.0.3 update that are cross-platform are also fixed:
    The most significant fixes in the Photoshop 12.0.3 update include the following:
    -- Windows XP tool tip font issue introduced by 12.0.2
    -- A number of potential security vulnerabilities have been addressed
    -- Top type and font crashers found in the field have been addressed
    -- A number of performance issues have been addressed
    -- Crash opening 3D layers has been addressed
    -- Color Engine crash has been resolved
    -- Intermittent file format issues addressed
    -- Shift scrolling bug fixed
    -- Sharpen crasher fixed
    -- Marching ants not seen at certain zoom levels fixed
    -- Metadata focus distance issue addressed
    -- File info bug addressed for Orphea Studio jpg's
    -- TWAIN crashers fixed
    -- Brush cursor bug fixed
    -- Histogram progress bar issue fixed
    -- Droplet issues addressed
    Thanks!

    Something has changed between 12.0.2 and and 12.0.4 with the pixel grid overlay at zooms > 500%.
    The pixel grid in 12.0.4 now uses 2 pixels "averaged." 12.0.2 used alternating rows and columns.
    At lower zooms (501% — 1000%) it looks better to me. At 1600% it looks fuzzier, but probably a bit more precise than the alternating method. Keep in mind this is just for screen drawing purposes. It doesn't affect the image.
    fyi.

Maybe you are looking for

  • How can I change the color of an event?

    iCal 4.0.4. Is there any way to use different colors for different events? Or for that matter, have more than two groups? I used Entourage for years and it has a calendar with plenty of options for using a variety of colors. For example, I had all my

  • Backup with Data Protector is not working

    Hello, [US]We have an Oracle DB which is saved by HP Data Protector [FR]Nous avons une BDD Oracle qui est sauvegardée via HP DataProtector. [US]During our last backup, the Data Protector Server has crashed which has stopped the backup during the proc

  • How do I transfer my music from my external hard drive with the extension .itl?

    I transferred my music from my old computer to an external hard drive.  Now trying to get my music to load into my new computer via external hard drive but I do not think it will due to the extension of .itl.  what shall I do?

  • Select the multiple nodes in a tree

    Hi Experts, We need to select the multiple nodes in a tree.Whatever we are selecting,that has to be added in the table as a tree structure itself. For ex: A |--A1     |--B1 If We select the A then A,A1 and B1 has to be added in a table.Please help me

  • Addition of new free char in query: Problem!

    Hi, I have a purchasing volume report . Requirement is to add the new characteritic     ( Material ) into the definition of the query! After adding the new characteristic, when i refreshed query in the workbook, the characteristic is displayed well b