How do I convert the below piece of java code to C++. I know I can write
typedef unsigned char byte so that is taken care of, but I don’t understand what the |= and <<= are meant for. And how does one replace final
public static final long unsignedIntToLong(byte[] b) {
long l = 0;
l |= b[0] & 0xFF;
l <<= 8;
(l >>> 4) & 0x0F;
How do I test all this in C++ – are there some unit tests I can run as I go about the conversion.
First thing,
|=is a compound bitwise OR assignment.a |= bis equivalent toa = a | b, where each resulting bit will be set if either that bit inaorbis set (or both).Here’s a truth table that is applied to each bit:
Secondly,
<<=is the same, but instead of a bitwise or, it’s a bit shift to the left. ALl existing bits are moved left by that amount, and the right is padded with 0s.finalis the same as C++’sconstby the variable definition. If, however, you want to prevent a function from being overriden, you may tagfinalonto the end of the function header if the function is also a virtual function (which it would need to be in order to be overriden in the first place). This only applies to C++11, though. Here’s an example of what I mean.Finally,
>>>is called theunsigned right shiftoperator in Java. Normally,>>will shift the bits, but leave the leftmost bit intact as to preserve the sign of the number. Sometimes that might not be what you want.>>>will put a 0 there all the time, instead of assuming that the sign is important.In C++, however,
signedis an actuality that is part of the variable’s type. If a variable is signed,>>will shift right as Java does, but if the variable is unsigned, it will act like the unsigned right shift (>>>) operator in Java. Hence, C++ has only the need for>>, as it can deduce which to do.