Tomoni
Tomoni

Reputation: 21

How to output the Binary value of a variable in C++

I've got a homework assignment in my C++ programming class to write a function that outputs the binary value of a variable's value.

So for example, if I set a value of "a" to a char I should get the binary value of "a" output.

My C++ professor isn't the greatest in the whole world and I'm having trouble getting my code to work using the cryptic examples he gave us. Right now, my code just outputs a binary value of 11111111 no matter what I set it too (unless its NULL then I get 00000000).

Here is my code:

#include <iostream>

#define useavalue 1

using namespace std;

void GiveMeTehBinary(char bin);

     int main(){

     #ifdef useavalue
     char b = 'a';
     #else
     char b = '\0';   
     #endif 

     GiveMeTehBinary(b);

     system("pause");

     return 0;

     }

     void GiveMeTehBinary(char bin){

     long s;

     for (int i = 0; i < 8; i++){

         s = bin >> i;

         cout << s%2;

         }

         cout << endl << endl;


     }

Thanks a ton in advance guys. You're always extremely helpful :)

Edit: Fixed now - thanks a bunch :D The problem was that I was not storing the value from the bit shift. I've updated the code to its working state above.

Upvotes: 2

Views: 7478

Answers (6)

silver takana
silver takana

Reputation: 186

it's actually really simple. to convert from decimal to binary you will need to include #include <bitset> in your program. inside here, it gives you a function that allows you to convert from decimal to binary form. and the function looks like this:

std::cout << std::bitset<8>(0b01000101) << std::endl;

the number 8 in the first argument means the length of the output string. the second argument is the value you want to convert. by the way, you can input a variable in binary form by declaring a 0b in front of the number to write it in binary form. note that to write in binary form is a feature added in c++14 so using any version lower than that won't work. here is the full code if you want to test it out.

#include <iostream>
#include <bitset>
int main()
{
    std::cout << std::bitset<8>(0b01000101) << std::endl;
}

note that you don't have to input a binary number to do this.

#include <iostream>
#include <bitset>
int main()
{
    std::cout << std::bitset<8>(34) << std::endl;
}

output:

00100010

Upvotes: 1

silver takana
silver takana

Reputation: 186

it's actually really simple. if you know how to convert decimal to binary, then you can code it easily in c++. in fact I have gone ahead and created a header file that allows you not only to convert from decimal to binary, it can convert from decimal to any number system. here's the code.

#pragma once
#include <string>

char valToChar(const uint32_t val)
{
    if (val <= 9)
        return 48 + val;
    if (val <= 35)
        return 65 + val - 10;
    return 63;
}
std::string baseConverter(uint32_t num, const uint32_t &base)
{
    std::string result;
    while (num != 0)
    {
        result = valToChar(num % base) + result;
        num /= base;
    }
    return result;
}

now, here is how you can use it.

int main()
{
    std::cout << baseConverter(2021, 2) << "\n";
}

output:

11111100101

Upvotes: 0

Chubsdad
Chubsdad

Reputation: 25487

#include <iostream>
using namespace std;
int main(){
   int x = 255;

   for(int i = numeric_limits<int>::digits; i >=0; i--){
      cout << ((x & (1 << i)) >> i);
   }
}

Upvotes: 0

cigarman
cigarman

Reputation: 651

Why not just check each bit in the unsigned char variable?

unsigned char b=0x80|0x20|0x01; //some test data
int bitbreakout[8];
if(b&0x80) bitbreakout[7]=1;
//repeat above for 0x40, 0x20, etc.
cout << bitbreakout;

There are a TON of ways to optimize this, but this should give you an idea of what do to.

Upvotes: 0

Loki Astari
Loki Astari

Reputation: 264331

Try this:

#include <bitset>
#include <iostream>
int main()
{
    std::bitset<8>      x('a');
    std::cout << x << std::endl;
}

Upvotes: 1

Konrad Rudolph
Konrad Rudolph

Reputation: 545488

The compiler should warn you about certain statements in your code that have no effect1. Consider

bin >> i;

This does nothing, since you don’t store the result of this operation anywhere.

Also, why did you declare tehbinary as an array? All you ever use is one element (the current one). It would be enough to store just the current bit.

Some other things:

  • NULL must only be used with pointer values. Your usage works but it’s not the intended usage. What you really want is a null character, i.e. '\0'.
  • Please use real, descriptive names. I vividly remember myself using variables called tehdataz etc. but this really makes the code hard to read and once the initial funny wears off it’s annoying both for you when you try to read your code, and for whoever is grading your code.
  • Formatting the code properly helps understanding a lot: make the indentation logical and consistent.

1 If you’re using g++, always pass the compiler flags -Wall -Wextra to get useful diagnostics about your code.

Upvotes: 6

Related Questions