in reply to Difference between Perl and Java for << operator?
JAVA RESULT: -268435456
PERL RESULT: 4026531840
Hope this simple little C program (compiled as C++) clarifies:
// tbs2.cpp // Built with: g++ -o tbs2 -std=c++11 -Wall -O3 tbs2.cpp (and with 32- +bit int) #include <cstdio> int main(int argc, char* argv[]) { printf("d : %d\n", -268435456); printf("u : %u\n", -268435456); printf("x : 0x%x\n", -268435456); return 0; }
Running this prints:
Though all 32 bits are the same (11110000000000000000000000000000), what is displayed depends on whether you interpret them as a signed int (%d) or an unsigned int (%u) or an unsigned int as a hexadecimal number (%x). Java is displaying the 32-bit value as a signed int (-268435456). Perl is displaying the identical value as an unsigned int (4026531840).d : -268435456 u : 4026531840 x : 0xf0000000
Sorry, I haven't used Java for twenty years, but Google tells me it has some sort of printf facility, so displaying your HIGH_BITS with Java printf with "%d" and "%u" - in addition to your System.out.print( HIGH_BITS ) - might be fun.
My original basic test C++ program:
// ANSI C++ 11: tbs1.cpp // Built with: g++ -o tbs1 -std=c++11 -Wall -O3 tbs1.cpp #include <cstdint> #include <iostream> int main(int argc, char* argv[]) { { int32_t HIGH_BITS = 0xFFFFFFFF << 28; std::cout << "int32 : HIGH_BITS = " << HIGH_BITS << "\n"; } { uint32_t HIGH_BITS = 0xFFFFFFFF << 28; std::cout << "uint32 : HIGH_BITS = " << HIGH_BITS << "\n"; } { int64_t HIGH_BITS = 0xFFFFFFFF << 28; std::cout << "int64 : HIGH_BITS = " << HIGH_BITS << "\n"; } { uint64_t HIGH_BITS = 0xFFFFFFFF << 28; std::cout << "uint64 : HIGH_BITS = " << HIGH_BITS << "\n"; } return 0; }
displays:
int32 : HIGH_BITS = -268435456 uint32 : HIGH_BITS = 4026531840 int64 : HIGH_BITS = 4026531840 uint64 : HIGH_BITS = 4026531840
Further update: For cheap thrills, let's display the bits.
// ANSI C++ 11: tbs4.cpp // Built with: g++ -o tbs4 -std=c++11 -Wall -O3 tbs4.cpp #include <cstddef> #include <cstdint> #include <cstdio> #include <iostream> #include <bitset> int main(int argc, char* argv[]) { printf("0xFFFFFFFF = %u\n", 0xFFFFFFFF); printf("0xF0000000 = %u\n", 0xF0000000); // This is the OP's 32-bit value HIGH_BITS const uint32_t HIGH_BITS = 0xFFFFFFFF << 28; std::cout << "HIGH_BITS = " << HIGH_BITS << "\n"; // Display all 32 bits 1 2 3 // 12345678901234567890123456789012 const std::bitset<32> b1{"11110000000000000000000000000000"}; std::cout << "b1 = " << b1 << "\n"; const std::bitset<32> b2{HIGH_BITS}; std::cout << "b2 = " << b2 << "\n"; return 0; }
Running this produces:
0xFFFFFFFF = 4294967295 0xF0000000 = 4026531840 HIGH_BITS = 4026531840 b1 = 11110000000000000000000000000000 b2 = 11110000000000000000000000000000
64-bit Data Model References
Updated: Minor changes were made to the originally posted code.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: Difference between Perl and Java for << operator?
by choroba (Cardinal) on Jul 30, 2021 at 09:19 UTC |