Bitwise Operators & IP Addresses

I am trying to determine an ip address class type ie:
Class A - 0 followed by 7 bits
Class B - 0 followed by 6 bits
Class C - 110 followed by 5 bits
The IP address & Subnet Mask are entered by the user
By ANDING the IP address and the subnet mask I have to determine whether the result is a class A, B or C IP address. I also have to return the Subnet address.
What is the approach I should take to doing this? Any help would be greatly appreciated!
Cheers!

Not exactly what you are looking for, but think I got it. I'm not Cisco Certified, but I think this seems to work. This is an IP address filter based on network prefix and netmask. Class C is shown. To filter Class A just make netmask 255.0.0.0, etc....
String testaddr = "10.1.0.137";
String netprefix = "10.1.0.0";
String netmask = "255.255.255.0"; //Class C netmask
int [] addr_arr = {0,0,0,0,0,0,0};
int [] ntmsk_arr = {0,0,0,0,0,0,0};
int [] prefx_arr = {0,0,0,0,0,0,0};
for (int indx = 4; indx !=0; indx = indx - 1)
addr_arr[indx] = Integer.parseInt(testaddr.substring(testaddr.lastIndexOf(".")+1));
ntmsk_arr[indx] = Integer.parseInt(netmask.substring(netmask.lastIndexOf(".")+1));
prefx_arr[indx] = Integer.parseInt(netprefix.substring(netprefix.lastIndexOf(".")+1));
if (testaddr.indexOf(".")!=-1)
testaddr =testaddr.substring(0,(testaddr.lastIndexOf(".")));
netprefix = netprefix.substring(0,(netprefix.lastIndexOf(".")));
netmask =netmask.substring(0,(netmask.lastIndexOf(".")));
if ( (addr_arr[indx] & ntmsk_arr[indx]) == prefx_arr[indx])
//System.out.println( "allow this packet" + addr_arr[indx] );
}else {return;} //quit here you failed filter test
//continue if you got this far......
System.out.println( "allow this packet" + addr_arr[indx] );
That was fun.

Similar Messages

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

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

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

  • 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

    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

  • Bitwise Operators - Different Output ?

    Hello !
    Can anyone please as to why these two different programs are giving different values ? Both are using Right
    Shift Operator >>> .
    The first shifts right the value a set to -1 to 24 bit positions giving a = 255 . But with the second program
    doing the same in a loop we start getting zero from the 9 iteration and continues till 24 ( and onwards ) . Why
    are we not getting the same value for a from the two programs ?
    // Right Unsigned Shifting : >>> ( Shift Right zero fill )
    class RUnsignShift {
    public static void main(String args[]) {
    int a = - 1 , b = 0 ;
    System.out.println("\nDemonstration : Right shift zero fill Operator >>> ");
    System.out.print("Original value int a = " + a +" ") ;
    System.out.println("Bit pattern : 11111111 11111111 11111111 11111111");
    b = a ;
    a = a >>> 24 ;
    System.out.print("a = -1 >>> 24 (Zero-fill) bit positions a = " + a +" ");
    System.out.println("Bit pattern : 00000000 00000000 00000000 11111111");
    b = b >> 24 ;
    System.out.print("b = -1 >> 24 (Sign Ext.) 24 bit positions b = " + b +"\n");
    SECOND PROGRAM
    class RUnsignShift2 {
    public static void main(String args[]) {
    int a = -1 , i ;
    System.out.println("Demonstration : Right shift zero fill Operator >>> ");
    System.out.print("Original value int a = " + a +" ") ;
    System.out.println("Bit pattern : 11111111 11111111 11111111 11111111");
    for(i = 0 ; i < 10 ; i++) {
    a = a >>> i ;
    System.out.println("a >>> " + i + " (Zero-fill) bit positions a = " + a +" ");
    //System.out.println("Bit pattern : 00000000 00000000 00000000 11111111");
    }

    NADEEMUDDIN wrote:
    a = a >>> 24 ;
    SECOND PROGRAM
    for(i = 0 ; i < 10 ; i++) {
    a = a >>> i ;
    System.out.println("a >>> " + i + " (Zero-fill) bit positions a = " + a +" ");
    //System.out.println("Bit pattern : 00000000 00000000 00000000 11111111");
    }The problem is that in your second program, a gets shifted with i meaning first time is a >>> 0, second time a >>> 1 etc. and all that it's equivalent with a >>> 45 at the end of the loop.
    To have the same results some changes must occur:
    for(i = 0 ; i < 24 ; i++) {
    a = a >>> 1 ;
    System.out.println("a >>> " + i + " (Zero-fill) bit positions a = " + a +" ");
    //System.out.println("Bit pattern : 00000000 00000000 00000000 11111111");
    }So in the final pass (24th) the a = a >>> 24.
    Cheers!

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

  • Bitshift operator and bitwise operators throwing errors

    Hi,
    I am using Java 1.4 on JDeveloper.
    When I try to complie following piece of code, its gives error:
    package myOtherPackage;
    class BitDemo {
        public static void main(String[] args) {
            int bitmask = 0x000F;
            int val = 0x2222;
            // prints "2"
            System.out.println(val & bitmask);
    }Error: method >>(java.lang.String, int) not found in class myOtherPackage.BitDemo.
    Kindly help me on this....

    Sorry ,
    Compilation completes but running it gives error when I keep this class in package. when took it out of package and defined as separate class, it runs fine...
    Error :
    Error(11,48): method &(java.lang.String, int) not found in class myOtherPackage.BitDemo
    Please look at error description. METHOD & .
    Edited by: J2EE_Life on Dec 26, 2011 8:56 AM
    Edited by: J2EE_Life on Dec 26, 2011 8:56 AM

  • SCJP prep help -- bitwise bad boys?

    Hi,
    I'm studying for SCJP so obviously one of the details I have to brush up on are the oft-unused bitwise operators: & | ^ ~
    I'm wondering if there are any mental techniques to using these in your head. Instead of literally writing out the number in binary, performing the comparison, and then re-converting back to decimal.
    Similar to how in grade school we learn that you can take a shortcut of multiplying two long numbers:
    34563
    x 24
    and do these steps:
    3 * 4 = 12, carry the 1
    6 * 4 = 24, add the 1 is 25, carry the 2
    5 * 4 = 20, add the 2 is 22, carry the 2
    4 * 4 = 16, add the 2 is 18, carry the 1
    3 * 4 = 12, add the 1, it all equals 138252
    next line
    then pad a zero on the right
    3 * 2 = 6
    6 * 2 = 12, carry the 1
    5 * 2 = 10, add the 1 is 11, carry the 1
    4 * 2 = 8, add the 1 is 9
    3 * 2 = 6, it all equals 691260
    altogether the answer is 691260 + 138252 = 829512
    In other words, while it's not feasible to add 34563 to itself 24 times (23 actually), there is a trick to figuring it out. Is there something like that for bitwise operators?
    Thanks.

    Thanks -- I finally collated some good tips a few days after I posted that here, with some help from local LUGgers. I'll post them here for the archives:
    Would you mind posting a summary of the helpful tips, tricks, and
    shortcuts sent your way? I'm rather interested in understanding this
    stuff a little better myself.Sure. In fact, they say you really know something well when you can
    explain it to someone else, and this gives anyone a chance to correct me
    if I'm wrong in what I think I know. Here's some of the things I
    learned, combined with what I had already learned from my book (please
    do correct me if I'm wrong):
    1. The unary bitwise NOT operator (~) has a shortcut, but one which
    only works when two's complement is in effect. On systems in which
    one's complement is in effect, it doesn't work. The shortcut is that
    any number n has a bitwise NOT of -n - 1. So
    ~5 == -6
    ~-12 == 11
    Because I'm fortunate enough to be working in Java where you're writing
    for only one platform (the JVM, which has a spec), I don't have to worry
    about exceptions to this for the test.
    2. Other than the NOT operator, the bitwise operators are binary
    operators, working on pairs of numbers. The bitwise AND operator
    returns a 1 for each pair of bits that are both 1.
    So in the case of
    11001 & 10011
    the result is 10001 (because only the first and last digits are both 1).
    The bitwise OR (|) operator returns a 1 for situations in which either
    pair of bits has a 1.
    So in the case of
    11001 | 10011
    the result is 11011 (because the only place in both numbers where there
    is no 1 is the third digit).
    The bitwise XOR (^) operator returns a 1 for situations in which either
    pair of bits, but not both, has a 1 (hence the name "exclusive OR", or XOR).
    So in the case of
    11001 ^ 10011
    the result is 01010 (because in the first, third, and fifth digits,
    either both numbers are 0 or 1).
    The short circuit operators AND (&&) and OR (||) work just like their
    regular counterparts except they stop evaluating once they "know" the
    result (AND stops evaluating if the first operand is false, and OR stops
    evaluating if the first operand is true).
    3. So my original question, "does anyone know any mental shortcuts for
    working with bitwise operators", should have been phrased as "does
    anyone know any mental shortcuts for converting decimal numbers to
    binary". The answer, which a couple of people provided, was that it's
    much easier to convert to binary (even if only in your head) when you
    are working from octal or hexadecimal, and that it's not too difficult
    to convert from decimal to octal or hexadecimal.
    Several ways were suggested:
    a) Convert the number to hex, then do the comparison a byte at a time in
    your head using a table:
    & 0x01 0x02 ... 0xff
    0x01 0x01 0x00 0x01
    0x02 0x00 0x02 0x02
    0xff 0x01 0x02 0xff
    b) Convert the number to octal using a simple recursive divide-by-eight
    solution:
    divide the number by eight, store the remainder as the low bit depth
    (rightmost number), then repeat the process with the quotient.
    123 / 8 = 15 remainder 3 -- 3 is rightmost digit (3)
    15 / 8 = 1 remainder 7 -- 7 is next to 3 (73)
    we don't divide 1 by 8 -- 1 is next to 7 (173)
    so 123 in octal is 0173
    From octal it's much easier to see the binary form of the number:
    1 7 3
    001 111 011
    And from binary it's much easier to do a bitwise calculation.
    c) Another way to convert to binary is to simply keep dividing by two
    and assigning 1 if there's a remainder and 0 if there isn't, then read
    in reverse to get the binary number:
    <quote>
    If a number is even, dividing it by 2 will have 0 remainder.
    If it is odd, dividing it by 2 will have a 1 remainder. Dividing
    by 2 is so easy that I, at least, can just write down a column of
    successive halvings, along with 1s and 0s for their oddness.
    459 1
    229 1
    114 0
    57 1
    28 0
    14 0
    7 1
    3 1
    1 1
    Reading from bottom to top, we again get 111001011. In this
    presentation you stop when the quotient is 1, since you've already
    written down the remainder that you'd get by dividing 1 by 2 when
    you write down the oddness. Remainder when dividing by 2 is easier
    than quotient.
    </quote>
    d) A final useful tip mentioned: as long as x is not zero,
    x & -x
    will always evaluate to a power of two, which means only one bit is set
    in the number (the least significant of the bits of x that were 1s).
    4. And everyone agreed that it's foolish to do these kinds of
    computations in your head when there's no good reason not to use a
    computer to do it. My personal preference is to use Python since the
    interactive interpreter works just like a calculator, though any
    scripting language should probably be able to handle the calculations.
    (Here's a quick sample:)
    |$ python
    |Python 2.2.2 (#1, Dec 31 2002, 12:24:34)
    |[GCC 3.2 20020927 (prerelease)] on cygwin
    |Type "help", "copyright", "credits" or "license" for more information.
    |>>> 12 & 14
    |12
    |>>> 12 | 14
    |14
    |>>> 12 ^ 14
    |2
    |>>> ~12
    |-13
    |>>> myResult = 0x5422CA66 & 458
    |>>> myResult
    |66
    |>>> hex(myResult)
    |'0x42'
    (hey, it wouldn't be a LUG without a little evangelism, would it? :)
    Much thanks to Bill, Jason, Kevin, and YATArchivist.
    Erik

  • 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

  • Bitwise Right Shift vs Divide by 2

    Something that just pondered across my mind.
    Bitwise operators have their uses, and I've always known about right/left shifting to divide/multiply by 2. I recently did some empirical analysis on an algorithm using this technique, and I had to iterate it over a trillion times before I started seeing any timing differences, and even then they were in the order of 0.0001 milliseconds.
    Is the performance argument for using bitwise over standard divide still applicable on modern day processors? When I use any kind of algorithms doing this kind of operation, they probably won't loop more than a few million times at most. For readability/understandability I may as well stick with divide by two.
    Perhaps it is only significantly faster in certain languages (e.g. C)?
    Regards,
    Rob.

    Yes. You are correct. In modern operators you will not gain anything by using shift operators in place of division. But the point is even though division, multiplication operators are available for you as a high level programmer, in processor level those operations not available. So multiplication and division are carried out using shift operations in the processor level. In hardware level, a processor supports only a few basic operations like addition, negation, shifting. But when you are using java, you are working at a very high layer so that even complex operators are available for you.
    Shift operators and other bitwise are very handy if you are manipulation some hardware from within your java application. If you are doing serial port/parallel port programming, you will find these bitwise operators useful.

Maybe you are looking for