1

I've a number between 0 and 63, so max 6 bits.
Then I've to represent this number in hexadecimal.

How can I force the reresentation of my number in 8 bits so that if I have:

int x = 60;
cout << std::hex << x; 

it prints 0x3C?

TobiMcNamobi
  • 4,687
  • 3
  • 33
  • 52
Luca Davanzo
  • 21,000
  • 15
  • 120
  • 146
  • 2
    I don't understand your question, but if what you want is "display 0x3c", then how about `std::cout << std::showbase << std::hex << x;` ? – user703016 Oct 02 '14 at 06:58
  • 2
    And if you want to “force the representation into 8 bits”, then use `std::unint8_t` instead of `int`. – 5gon12eder Oct 02 '14 at 07:04
  • "hex" notation pretty much assumes you have an 8 bit byte. The binarys "00000000" to "11111111" are display in the range x'00' to x'FF'. – James Anderson Oct 02 '14 at 07:09
  • 60 is *always* represented in 8 bits (the upper two being 0). – Peter - Reinstate Monica Oct 02 '14 at 07:11
  • @PeterSchneider: The literal has type `int` which means it has at least 10 bits set to zero, if not 26. `char(60)` would have _at least_ 8 bits, but in general `CHAR_BITS`. – MSalters Oct 02 '14 at 07:14
  • Related: http://stackoverflow.com/questions/5100718/int-to-hex-string-in-c – TobiMcNamobi Oct 02 '14 at 07:21
  • @MSalters I'm aware of the size of various data types on various platforms; still, none of those bits are used to represent a value of 60. I am deliberately misunderstanding because the OP didn't make himself clear. Does he just want output formatted the way his example shows? What keeps him? Not a lack of online documentation of output formatting. Or does he want to have the memory representation in 8 bit? That may be impossible since he never takes the address so that the number may stay in a register which is usually larger. I think he is conceptually not distinguishing the two. – Peter - Reinstate Monica Oct 02 '14 at 07:22
  • @PeterSchneider `60` is an `int`; on my machine, it is represented in 32 bits. – James Kanze Oct 02 '14 at 08:20
  • @James Of course. The zero bits are, strictly spoken, part of the representation (the value would differ after all were they not zero). "This page intentionally left blank" (original HP documentation). But then x may never occupy *any* "memory" in the given example because it may have storage class register. (To stay in the image: The documentation was never printed; there never was a "page".) How the value is represented is irrelevant; there are 6 significant bits. The compiler would certainly be free to store x in a byte register if it had one. Or eliminate it altogether, for that matter. – Peter - Reinstate Monica Oct 02 '14 at 08:31

1 Answers1

4

try this :

#include<iostream>
#include <iomanip>
using namespace std;

}
int main(){
    int x = 60;
    cout<<showbase; // show the 0x prefix
    cout<<hex<<x; 
    return 0;
}

output :

0x3c
Rustam
  • 6,485
  • 1
  • 25
  • 25