0

I'm trying to transfer a C# function to C++ but ran into a lovely problem I've never seen nor needed before. Everything has transfer quite nicely except for a bit shift line.

C# - Works without problems.

long val = 2791804260201463808; 
int Cap = (int)val; //-608501760
val = (long)((ulong)val >> 32);
return val;  // this returns 650017582

Now transfer to C++

C++ - Compile error "warning C4293: '>>': shift count negative or too big, undefined behavior"

long val = 2791804260201463808;
int Cap = (int)val; //-608501760
val = (long)((ulong)val >> 32); 
return val;  // this returns -608501760 - No change, as if bit shift was skipped

How can I transfer this? I'm having a problem seeing out of my box.

I've tried different variable types with no luck.

  • @madreflection Maybe not "often". These days it's only the MSVC compiler which is using 32-bit `long` on 64-bit systems. – Some programmer dude Dec 04 '22 at 06:38
  • 1
    *Now transfer to C++* -- In C# and other languages, those integer types have a defined size. In C++, use `uint32_t`, `int32_t`, `uint64_t`, etc. Those types state the bitness you are trying to achieve. – PaulMcKenzie Dec 04 '22 at 06:45
  • 2
    `ulong` is not a standard type in C++. If it is a type of `32` bits or less (the number of bits in an `unsigned long` or in a `long` is implementation-defined, but 32 bits is common in practice) then shifting 32 bits or more gives undefined behaviour. `long` and `ulong` in C# are 64 bits. In C++, to get 64 bits you need to use types which are guaranteed to have enough bits, such as like `unsigned long long` and `long long`. Since C++11 you can `#include ` and use `std::int64_t` and `std::uint64_t` or related types. – Peter Dec 04 '22 at 06:49
  • This might help: https://learn.microsoft.com/en-us/cpp/code-quality/c26452?view=msvc-170#:~:text=This%20warning%20indicates%20the%20shift%20count%20is%20negative%2C,a%20similar%20check%20in%20the%20Microsoft%20C%2B%2B%20compiler. – Vic F Dec 04 '22 at 18:50

0 Answers0