0

Here I have 2 functions one is in c++ and one is Java. Both have the same purpose: C++:

void VarIntToBufferArray(int* buffer, int in) { std::vector<int> buffVect; int value = in; do { int temp = (int)(value & 0b01111111); value >> 7; if (value != 0) { temp |= 0b10000000; } buffVect.push_back(temp); } while (value != 0); buffer = &buffVect[0]; } 

Java:

public static void writeVarInt(int value) { do { byte temp = (byte)(value & 0b01111111); // Note: >>> means that the sign bit is shifted with the rest of the number rather than being left alone value >>>= 7; if (value != 0) { temp |= 0b10000000; } writeByte(temp); } while (value != 0); } 

Something is wrong with C++ version of code because I get this output on C++: 0 0 99 -35 and on Java version: -35 -57 1 which should be. I think >> by itself can't replace >>>=. Any way of doing that?

8
  • 7
    value >> 7; is a no-op. Did you mean value >>= 7;? But for the equivalent of >>>, you probably need value = int(unsigned(value) >> 7); In Java, a separate operator for "unsigned shift" is needed because Java lacks unsigned integral types. Commented Nov 1, 2020 at 23:15
  • In Java, do you mean the >>= operator? Commented Nov 1, 2020 at 23:16
  • With value = int(unsigned(value) >> 7);, I get output: -858993460 -858993460 -858993460 -858993460 Commented Nov 1, 2020 at 23:23
  • What do you mean, you get output? The C++ code you've shown doesn't produce any output. In fact, the whole VarIntToBufferArray is an elaborate no-op, as it doesn't have any side effects. Commented Nov 1, 2020 at 23:26
  • int buffer[sizeof(int)]; VarIntToBufferArray(buffer, 25565); Commented Nov 1, 2020 at 23:27

1 Answer 1

0

Solved: (Now getting same output as in Java)

template<typename T> void convertUnderByteMax(T* temp) { if (*temp > 127) { *temp -= 256; } } void VarIntToBufferArray(std::vector<int>& buffer, int in) { int value = in; do { int temp = (int)(value & 0b01111111); value = ((unsigned int) value) >> 7; if (value != 0) { temp |= 0b10000000; } convertUnderByteMax(&temp); buffer.push_back(temp); } while (value != 0); } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.