简体   繁体   中英

Simple Conversion from C++ to Java

I am tasked with porting this C++ code over to Java. I am much better with Java than I am with C++. I understand bit-shifting to a large extent, but I don't really understand what the unsigned long value is doing in this context.

What would this look like in Java?

#include <iostream>
using namespace std;

int main() {
   short netSpeed = 3;    
   cout << "netSpeed before: " << netSpeed << endl;

   netSpeed = 1UL << netSpeed;
   cout << "netSpeed after: " << netSpeed << endl; 

   return 0;
}

The C++ developer is not taking any chances with a platform's representation of an signed integral type, which could be 1's or 2's complement. They are also guarding themselves against undefined behaviour due to overflow of the integral value 1 which could be as small as a 16 bit int .

Using a 1UL is giving them reassurance that the result of the shift will be 0b1000. UL is forcing the compiler to use an unsigned long type.

Actually it's superfluous in this case, and given that Java always uses 2's complement for integral types (and they are all signed, aside from the char type), it's perfectly safe for you to write 1 << netSpeed in your Java port.

This is the exact conversion of your code from C++ to Java:

class Speed {
    public static void main(String args[]) {
       short netSpeed = 3;
       System.out.println("netSpeed before: "+netSpeed);

       netSpeed = (short) (1 << netSpeed);
       System.out.println("netSpeed after: "+netSpeed);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM