Sidharth Tripathi
Sidharth Tripathi

Reputation: 45

conversion of integers into binary in c++

As we know, each value is stored in binary form inside memory. So, in C++, will these two values have different binary numbers when stored inside memory ?

unsigned int a = 90;
signed int b = 90;

Upvotes: 1

Views: 186

Answers (2)

eerorika
eerorika

Reputation: 238301

So, in C++, will these two values have different binary numbers when stored inside memory ?

The C++ language doesn't specify whether they do. Ultimately, the binary representation is dictated by the hardware, so the answer technically depends on that.

That said, I haven't encountered hardware and C++ implementation where identically valued signed and unsigned variants of an integer didn't have identical binary representation. As such, I would find it surprising if the binary representations were different.


Sidenote: Since "byte" is the smallest addressable unit of memory in C++, there isn't a way in the language to observe a directional order of individual bits in memory.

Upvotes: 2

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122133

Consider the value 63. In binary it is 111111 and in hex it is 3f.

Because char is special in C++, and any object can be viewed as a sequence of bytes, you can directly look at the binary representation:

#include <iostream>
#include <iomanip>

int main()
{
    unsigned int a = 63;
    signed int b = 63;

    std::cout << std::hex;

    char* a_bin = reinterpret_cast<char*>(&a);
    for (int i=0; i < sizeof(unsigned int); ++i) 
        std::cout << std::setw(4) << std::setfill('0') << static_cast<unsigned>(*(a_bin+i)) << " ";

    std::cout << "\n";

    char* b_bin = reinterpret_cast<char*>(&b);
    for (int i=0; i < sizeof(signed int); ++i) 
        std::cout << std::setw(4) << std::setfill('0') << static_cast<unsigned>(*(b_bin+i)) << " ";   
}

Unfortunately, there is no std::bin io-manipulator, so I used std::hex (it is sticky). The reinterpret_cast is ok, because of the aforementioned special rules for char. Because std::cout << has special overload to print characters, but we want to see numerical values, another cast is needed. The output of the above is:

003f 0000 0000 0000 
003f 0000 0000 0000 

Live Demo

As already mentioned in a comment, the byte order is implementation defined. Moreover, I have to admit that I am not aware about the very details of what the standard has to say about this. Be careful with assumptions about byte representation, especially when transfering objects between two programs or over a wire. You would typically use some form of de-/serialization, such that you are in control of the byte representations to be transfered.

TL;DR: Typically yes, in general you need to carefully consider what the C++ standard mandates, and I am not aware of signed and unsigned being guaranteed to have same byte representations.

Upvotes: 1

Related Questions