473,414 Members | 1,596 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,414 software developers and data experts.

write binary representation to output

Dear all,
I was wondering how in C++ the code would look like if I want to write
the binary notation of a unsigned char to standard output or any other
basic data type, like int, unsigned int, float and so forth.
Thanks in advance.
RR
Jun 27 '08 #1
7 2387
wo*********@yahoo.com wrote:
I was wondering how in C++ the code would look like if I want to write
the binary notation of a unsigned char to standard output or any other
basic data type, like int, unsigned int, float and so forth.
#include <iostream>
#include <climits>

template<typename Type>
void printBinaryRepresentation(const Type& value)
{
// Resolve if this is a big-endian or a little-endian system:
int dummy = 1;
bool littleEndian = (*reinterpret_cast<char*>(&dummy) == 1);

// The trick is to create a char pointer to the value:
const unsigned char* bytePtr =
reinterpret_cast<const unsigned char*>(&value);

// Loop over the bytes in the value:
for(unsigned i = 0; i < sizeof(Type); ++i)
{
unsigned char byte;
if(littleEndian) // we have to traverse the value backwards:
byte = bytePtr[sizeof(Type) - i - 1];
else // we have to traverse it forwards:
byte = bytePtr[i];

// Print the bits in the byte:
for(int bitIndex = CHAR_BIT-1; bitIndex >= 0; --bitIndex)
{
std::cout << ((byte >bitIndex) & 1);
}
}

std::cout << std::endl;
}
Jun 27 '08 #2
* wo*********@yahoo.com:
>
I was wondering how in C++ the code would look like if I want to write
the binary notation of a unsigned char to standard output or any other
basic data type, like int, unsigned int, float and so forth.
E.g.

<code>
#include <iostream // std::cout, std::ostream
#include <ostream // operator<<, std::endl
#include <bitset // std::bits
#include <climits // CHAR_BIT

static unsigned const bitsPerByte = CHAR_BIT;

template< typename T >
struct BitSize
{
enum { value = bitsPerByte*sizeof( T ) };
};

template< typename T >
std::bitset< BitSize<T>::value bitsetFrom( T const& v )
{
typedef std::bitset< BitSize<T>::value BitSet;

BitSet result;
unsigned char const* p = reinterpret_cast<unsigned char const*>( & v );

// Uses little-endian convention for bit numbering.
for( size_t i = sizeof(T)-1; i != size_t(-1); --i )
{
result <<= bitsPerByte;
result |= BitSet( p[i] );
}
return result;
}

int main()
{
using namespace std;

int const i = 1234;
float const f = 1234.567;

cout << bitsetFrom( i ) << endl;
cout << bitsetFrom( f ) << endl;
}
</code>
Cheers, & hth,.

- Alf
Jun 27 '08 #3
On 19 avr, 10:19, Juha Nieminen <nos...@thanks.invalidwrote:
wongjoek...@yahoo.com wrote:
I was wondering how in C++ the code would look like if I
want to write the binary notation of a unsigned char to
standard output or any other basic data type, like int,
unsigned int, float and so forth.
#include <iostream>
#include <climits>
template<typename Type>
void printBinaryRepresentation(const Type& value)
{
// Resolve if this is a big-endian or a little-endian system:
int dummy = 1;
bool littleEndian = (*reinterpret_cast<char*>(&dummy) == 1);
And what about middle endian? If a type has more than two
bytes, then more than two orders are possible, and in fact, I've
seen at least three for long (on very common machines, no less).

For the rest, I don't think that this is what he was looking
for, and even if it was, I don't see any reason to access byte
by byte.

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Jun 27 '08 #4
James Kanze wrote:
And what about middle endian?
Most probably we can ignore obscure architectures.
For the rest, I don't think that this is what he was looking
for, and even if it was, I don't see any reason to access byte
by byte.
How else? The size of the type will be n bytes, so accessing byte by
byte is the most logical choice. How else would you do it?
Jun 27 '08 #5
"wo*********@yahoo.com" <wo*********@yahoo.comwrites:
Dear all,
I was wondering how in C++ the code would look like if I want to write
the binary notation of a unsigned char to standard output or any other
basic data type, like int, unsigned int, float and so forth.
Thanks in advance.
RR
How about this:

#include <iostream>
#include <iomanip>

template<typename Tstruct binary_traits
{
typedef T int_t;
};

template<struct binary_traits<float>
{
typedef int int_t;
};

template<struct binary_traits<double>
{
typedef long long int_t;
};

template<typename T>
void output(T x)
{
std::cout << std::setw(sizeof(x)*2) << std::setfill('0') << std::hex
<< * reinterpret_cast<typename binary_traits<T>::int_t *>(&x)
<< std::endl;
}

int main(int argc, char *argv[])
{
output(10);
output(10L);
output(10LL);
output(0.1f);
output(0.1);

return 0;
}

--
Charles M. "Chip" Coldwell
"Turn on, log in, tune out"
GPG Key ID: 852E052F
GPG Key Fingerprint: 77E5 2B51 4907 F08A 7E92 DE80 AFA9 9A8F 852E 052F
Jun 27 '08 #6
On 20 avr, 11:41, Juha Nieminen <nos...@thanks.invalidwrote:
James Kanze wrote:
And what about middle endian?
Most probably we can ignore obscure architectures.
That was a Microsoft compiler, on an Intel architecture. I
don't know that the word "obscure" is appropriate in such cases.
For the rest, I don't think that this is what he was looking
for, and even if it was, I don't see any reason to access byte
by byte.
How else? The size of the type will be n bytes, so accessing
byte by byte is the most logical choice. How else would you do
it?
As itself?

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Jun 27 '08 #7
James Kanze wrote:
>>For the rest, I don't think that this is what he was looking
for, and even if it was, I don't see any reason to access byte
by byte.
>How else? The size of the type will be n bytes, so accessing
byte by byte is the most logical choice. How else would you do
it?

As itself?
How do you access individual bits of a double? (Or a struct containing
several member variables, for example.)
Jun 27 '08 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Mark Dufour | last post by:
Hi all, I need to convert an integer into some binary representation. I found the following code in the online cookbook (adapted to return a list): binary = lambda n: n>0 and +binary(n>>1) or ...
4
by: Rouben Rostamian | last post by:
Consider the following demo program: #include <stdio.h> int main(void) { unsigned char c; for (c=0; c<15; c++) putchar(c);
10
by: 63q2o4i02 | last post by:
Hi, I'm using python to run some lab equipment using PyVisa. When I read a list of values from the equipment, one of the fields is 32 bits of flags, but the value is returned as a floating...
3
by: Billy Smith | last post by:
I'm trying to write a little utility that will write some binary data to a file via a javascript and Windows Script Host under Windows XP. The only way to do this that I can find is to convert...
3
by: shyha | last post by:
Hello! Does anybody know what is binary representation of integer datatype fields written to archlogs on z/OS (OS/390) machines? Is it "Two's complement", "One's complement", Sign-modulo or...
5
by: Andrea | last post by:
Hi, I'm a newbie i want to know how can i convert string to its binary representation, i want to write a program where an example string "hello world" is transformed in his binary representation...
26
by: Carramba | last post by:
Hi! How can I output value of char or int in binary form with printf(); ? thanx in advance
1
by: krishna81m | last post by:
I am a newbie and have been trying to understand conversion from double to int and then back to int using the following code was posted on the c++ google group. Could someone help me out with...
7
by: eliben | last post by:
Hello, I'm interested in converting integers to a binary representation, string. I.e. a desired function would produce: dec2bin(13) ="1101" The other way is easily done in Python with the...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.