1

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;
}
EdgeCase
  • 4,719
  • 16
  • 45
  • 73
  • Did you try to run it and check what it does...? – Melkon Sep 08 '15 at 15:43
  • Possible Duplicate of http://stackoverflow.com/questions/9854166/declaring-an-unsigned-int-in-java – burglarhobbit Sep 08 '15 at 15:44
  • 3
    you are much better with java than c++ but you don't know how to print to the console? do you see the contradiciton – David Haim Sep 08 '15 at 15:44
  • Of course I ran it. Did you read my question? I was wondering about the 1UL.\ – EdgeCase Sep 08 '15 at 15:53
  • You're doing bit shifting so this doesn't matter here, but if you start playing at the byte level The Big Weird will probably be Java always exposes big endian and C++ will be platform dependent endian. If numbers read back insane values, check the endian. – user4581301 Sep 08 '15 at 17:50

2 Answers2

2

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.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • I'm not sure I buy that. The resulting value (1 << 3) is 8, which is guaranteed to be representable by `int` in C++, so I'm not sure what kind of chances the developer isn't taking. – Kerrek SB Sep 08 '15 at 16:01
  • I've seen this kind of thing before by less than confident C++ developers. I do state (perhaps not clearly enough) that it's superfluous. – Bathsheba Sep 08 '15 at 16:01
-1

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);
    }
}
Ho1
  • 1,239
  • 1
  • 11
  • 29