2

I am learning about how to work with binary numbers to optimize some programs, and I was reading about the process to convert a binary number to an integer. The process is the two’s complement process. Given a binary number, like 1011 0100, could be 180 or -76. It depends on the type, right? But when I want to obtain -76, I always obtain 180. I want to know how I can get -76 The code to print 180:

#include <iostream>

using namespace std;

int main(){
  uint8_t num{0b1011'0100};
  
  cout<<static_cast<int>(num);
  return 0;
}

I tried with int8_t, but I get the next error:

error: narrowing conversion of ‘180’ from ‘int’ to ‘int8_t’ {aka ‘signed char’} [-Wnarrowing] 6 | int8_t num{0b1011'0100};

9
  • How are you optimizing programs using binary numbers? Usually, the numbers stored in memory are binary; decimal and hex is only used for human readability. Commented Dec 6, 2022 at 0:52
  • @ThomasMatthewsfor example, if i need to have a lot of "boolean" values verifying differents states of a lot of elements (for example in a video game). the boolean type need 1 byte (8 bits), so i was reading that i can use the Bit manipulation with bitwise operators and bit masks to seize the bits that i don t use Commented Dec 6, 2022 at 0:56
  • @Lkx8888 For such task, you should only be using unsigned types. Commented Dec 6, 2022 at 0:58
  • It's usually faster to waste a little bit of memory and use a full byte for each boolean, so that's what most video games will do. Commented Dec 6, 2022 at 0:59
  • 1
    @Lkx8888: You are optimizing for space not speed. Your program will need to use binary operations in order to extra bits from the data type; that takes extra time. Using an array of unsigned integers would be a lot faster, as the processor doesn't need to extract bits. Commented Dec 6, 2022 at 1:00

1 Answer 1

2
uint8_t num{0b1011'0100}

What you have here, is a std::uint8_t with the value 180.

As I understand, your goal is to get the value -76 using conversions. The problem with converting to int is that 180 is representable in that type, so the result of the conversion will be 180.

What you can do instead, is convert to std::int8_t:

std::int8_t num_s = num; // value will be -76

You'll still face the problem that would encounter with std::uint8_t when inserting to standard output. Since those types are aliases of character types, they will be output as symbols, so num_s must also be converted to int just like num is converted in your example.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.