You are here:

C++/how to convert binary to hex (c++) and other questions as well



I really need some help on c++. This is my first time using it and i get confused.

Here are my questions:

1.) how would you convert a binary to hexadecimal.
im getting a string input. eg. (10010001) as a string. i accept up to 32 bit.

2.) How would you convert a uintvar value from the user to decimal.

This is the algorithm but i dont get it.

To decode a uintvar into a decimal/integer:
discard MSB of each byte  and concatenate all reamaining 7 bits of each byte. find the integer value represented by the resulting binary number. Note that the last of the iput bytes have their MSBs set to 1. while the last byte its MSB is 0.

example output:

8a5c: 1372
8102: 130
9a81: 0
7f:   127

This is basically the reverse of this :

Thanks. Help is much appreciated.

To deal with bits (numbers to strings of 0's and 1's etc) use std::bitset<>

To convert anything from or to a string use std::istringstream / std::ostringstream.

#include <iostream>
#include <string>
#include <bitset>
#include <sstream>
#include <algorithm>

std::string binary_to_hex( const std::string& bits )
   constexpr std::size_t MAX_BITS = 32 ;
   std::ostringstream stm ;
   stm << std::hex << std::bitset<MAX_BITS>( bits, 0, MAX_BITS ).to_ulong() ;
   return stm.str() ;

// get the least significant 7 bits in a byte
std::string seven_bits( const std::string& hex_byte )
   std::istringstream stm(hex_byte) ;
   unsigned int b ;
   stm >> std::hex >> b ;
   return std::bitset<8>(b).to_string().substr(1) ;

std::string uintvar_to_decimal( const std::string& uintvar )
   constexpr std::size_t MAX_BITS = 64 ;
   const std::size_t NBYTES = std::min( uintvar.size()/2, MAX_BITS/8 ) ;

   std::string bits ;

   for( std::size_t i = 0 ; i < NBYTES ; ++i ) // for each byte
       bits += seven_bits( uintvar.substr( i*2, 2 ) ) ; // add the 7 lsb to bits
   std::ostringstream stm ;
   stm << std::bitset<MAX_BITS>(bits).to_ullong() ; // convert to decimal number
   return stm.str() ;

int main()
   const std::string bits = "1111111100010010001101001011" ;
   std::cout << binary_to_hex(bits) << '\n' ;

   const std::string uintvar = "8a5c" ;
   std::cout << uintvar_to_decimal(uintvar) << '\n' ;



All Answers

Answers by Expert:

Ask Experts




my primary areas of interest are generic and template metaprogramming, STL, algorithms, design patterns and c++11. i would not answer questions about gui and web programming.


about 15 years or so

post graduate engineer

©2017 All rights reserved.