Bens Stuff

Thursday, June 17, 2004

Shifty bits

I was looking at this Javaranch journal entry about shifting bits and it got me thinking. I remember having to do that stuff in Assembly and later in C back when I was in school, but I have yet to find a practical use for it in my daily work. What do people use bit shifting for in the real world? As a Java web developer, why would I shift any bits around?

3 Comments:

  • For example to create bit masks. I for one used it the other day o create a bit mask for verifying if a long contained a valid bluetooth address. A valid bluetooth address is 48 bits long, a long (in java) is 64. Thus you can verify it by checking if ( address & mask ) == address.

    As my class uses the length of the bluetooth address at several places (e.g. when converting the long to the standard string representation), I didn't want to hard code the mask (which is 0xffffffffffffL), and separately hard code the length of the bluetooth address as they are closely related. I wrote a simple loop using shifts to create the mask (with other necessary constants depending on the address length) in a static initializer:

    long digitMask = 0xfL;
    long mask = 0;
    for ( int i = 0; i < BD_ADDR_LENGTH * 2; i++ ) {
    mask |= digitMask << i * 4;
    }

    ADDRESS_MASK = mask;

    By Anonymous Anonymous, at 1:04 PM  

  • well, we use bit operations for performance and resource concerns. . but they are not necessary in most cases .

    we are trying to develop a grammar and spell checking engine for turkish. because of the nature of turkish, it is a hard and slow task. it requires to be very fast because it will serve multiple users.
    there is a hash map carrying the root words, but as key, instead of string, i am producing a int value by myself. Because calculating the hash value of a string, or creating one is a time consuming operation. anyway, there are some details i will not mention, we used bit shifting, XOR operations for calculating a fast hash array from a string. we gain %30-%50 performance win for that operation.
    Also for bit mask fields it might be useful. for attributes of a word (there can be lets say 10 attributes) instead of using booleans, you can use bits and bit test methods. it saves momory, but we havent activated that code yet becuase memory use is still "ok" and booleans are easier to use. there is a trade off.
    Also in crypto, image processing, scientific applications algorithms bit operations and shifting is used extensively.

    By Blogger Chiko Lopez, at 3:55 PM  

  • Yes,you certainly are a pretty one.

    By Anonymous Anonymous, at 11:21 AM  

Post a Comment

<< Home