473,604 Members | 2,487 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to use std::cout to output a char as a number?

Hi, everyone

It might be a simple question, but I really don't know the answer.

char c = '1';
cout << c;

The above code will only output a '1' rather than 0x31;

If I use int cast, it can show the number:

cout << (int) c;

however, if the c is 0x80, which might be a part of MBCS(multibyte
character set) string, such as :

const char* cc = "\xba\xba";
cout << hex << "0x" << (int)cc[0] << ", 0x" << (int)cc[1] << endl;

it will extend negative bit, and will output as:

0xFFFFFFBA, 0xFFFFFFBA

I currently use a stupid way to avoid extending the negative bit and
show the number of a simple char by double casting:

const char* cc = "\xba\xba";
cout << hex << "0x" << (unsigned short)((unsigne d char)cc[0]) << ",
0x" << (unsigned short)((unsigne d char)cc[1]) << endl;

This time the output looks ok. But it doesn't make any sense, since I
only want to output the char as a number, should not so complicated by
double casting.

Did I miss anything? What is the most directly way to use std::cout
output a char as a number?

Thanks.

Apr 30 '07 #1
19 33355
Dancefire wrote:
Hi, everyone

It might be a simple question, but I really don't know the answer.

char c = '1';
cout << c;

The above code will only output a '1' rather than 0x31;

If I use int cast, it can show the number:

cout << (int) c;

however, if the c is 0x80,[..]
See, this is where the logic fails you. An 8-bit char cannot
have the value 0x7f, unless it's implemented as unsigned. If
it's a signed char (as you seem to show), 0x7f is its highest
possible value.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Apr 30 '07 #2
If I use int cast, it can show the number:
>
cout << (int) c;
however, if the c is 0x80,[..]

See, this is where the logic fails you. An 8-bit char cannot
have the value 0x7f, unless it's implemented as unsigned. If
it's a signed char (as you seem to show), 0x7f is its highest
possible value.
Yes, define the 'unsigned char' works for above case. Thank you.

But I still have the problem. The original problem is raised when I
try to print a std::string's content as number for each character. The
standard define the string is basic_string<ch ar, ...>, is not
bacic_string<un signed char, ...>. Currently, I have to use the
following loop to show each character as a number:

string test("\xba\xba" );
for(std::string ::iterator iter = test.begin(); iter != test.end(); +
+iter)
{
cout << "0x" << hex << (unsigned short)((unsigne d char) *iter) <<
" ";
}

The *iter is char, not unsigned char. So, I have to use double casting
to do the job. If I use c-style function, I can easily specify "%x" in
the format string of printf() to print the char without any
unnecessary casting, it looks much straightforward . In C++'s
std::cout, there should be a way that easily specify whether I want to
print a character, or a numeric value, rather than determine by cout
itself, since the 'char' is really special, sometimes it's character,
sometime, it means a 8-bit integer number.

Apr 30 '07 #3
On 30 Apr 2007 04:52:22 -0700, Dancefire wrote:

[...]
>const char* cc = "\xba\xba";
cout << hex << "0x" << (unsigned short)((unsigne d char)cc[0]) << ",
0x" << (unsigned short)((unsigne d char)cc[1]) << endl;

This time the output looks ok. But it doesn't make any sense, since I
only want to output the char as a number, should not so complicated by
double casting.

Did I miss anything? What is the most directly way to use std::cout
output a char as a number?
What do you mean by most direct way? You could write something like
the following:

unsigned
as_unsigned( char c )
{
return static_cast< unsigned char >( c );
}

(note: if c is negative, the cast to unsigned char will yield the
mathematical value UCHAR_MAX + c, regardless of whether char uses a
two's complement representation or not)

--
Gennaro Prota
https://sourceforge.net/projects/breeze/
Apr 30 '07 #4
On Mon, 30 Apr 2007 16:25:12 +0200, Gennaro Prota wrote:
>(note: if c is negative, the cast to unsigned char will yield the
mathematical value UCHAR_MAX + c, regardless of whether char uses a
two's complement representation or not)
Of course I meant to write UCHAR_MAX + 1 + c, sorry.

--
Gennaro Prota
https://sourceforge.net/projects/breeze/
Apr 30 '07 #5
>
Did I miss anything? What is the most directly way to use std::cout
output a char as a number?

What do you mean by most direct way? You could write something like
the following:

unsigned
as_unsigned( char c )
{
return static_cast< unsigned char >( c );
}

(note: if c is negative, the cast to unsigned char will yield the
mathematical value UCHAR_MAX + c, regardless of whether char uses a
two's complement representation or not)

--
Gennaro Protahttps://sourceforge.net/projects/breeze/
Thanks for reply, do I have to use a function to do this? It involve
much more overhead. Not only the function call, but also I should put
the function to some where my every time cout << char can see the
code, which means I should put the function into my function lib.

And the above function still cannot output the number, it's will still
output the character, Unless I call another casting to cast the
unsigned char to unsigned short. It's not better than just double
casting the char at the place I output it. which is provide at
original post:

cout << " 0x" << hex << static_cast<uns igned
short>(static_c ast<unsigned char>(c));

But this form is not semantically correct, I only want to output the 8-
bit unsigned integer, rather than 16-bit unsigned integer. And I use 2
casting only for correct output the char as a number? Is there any
other way to do that? is there anything just like the printf("%x", c)
in cout, which means I set something, and then the output for char is
a number. Such as:

cout << " 0x" << hex << char_is_number << c;

or

cout << " 0x" << hex << static_cast<*a simple type here*>(c);

Thanks.

Apr 30 '07 #6
On 30 Apr 2007 09:25:46 -0700, Dancefire wrote:
>Did I miss anything? What is the most directly way to use std::cout
output a char as a number?

What do you mean by most direct way? You could write something like
the following:

unsigned
as_unsigned( char c )
{
return static_cast< unsigned char >( c );
}

(note: if c is negative, the cast to unsigned char will yield the
mathematical value UCHAR_MAX + c, regardless of whether char uses a
two's complement representation or not)

[sig snipped...]

Thanks for reply, do I have to use a function to do this? It involve
much more overhead. Not only the function call,
You shouldn't be concerned with that. Try for instance googling for
"premature optimization".
>but also I should put
the function to some where my every time cout << char can see the
code, which means I should put the function into my function lib.
What's wrong with that?
>And the above function still cannot output the number, it's will still
output the character, Unless I call another casting to cast the
unsigned char to unsigned short.
No. First the function performs no output, just a (double) conversion.
Secondly, the return type is unsigned int, not unsigned char. Try

std::cout << as_unsigned( c );
>It's not better than just double casting the char at the place
It's better than double casting "in place" for at least two reasons:
a) it gives a name to the operation you perform b) it encapsulates the
way you do it: should you later discover that the way you did it is
incorrect, you just have to fix it in one place.

And, of course, you should anyway use new-style casts.
>I output it. which is provide at original post:

cout << " 0x" << hex << static_cast<uns igned
short>(static_ cast<unsigned char>(c));

But this form is not semantically correct,
You lost me here. Didn't you say in your original post that this gives
what you want?
>I only want to output the 8-
bit unsigned integer, rather than 16-bit unsigned integer.
What's the difference on output if your unsigned int has at most 8
bits on?
>And I use 2
casting only for correct output the char as a number? Is there any
other way to do that? is there anything just like the printf("%x", c)
in cout, which means I set something, and then the output for char is
a number. Such as:

cout << " 0x" << hex << char_is_number << c;

or

cout << " 0x" << hex << static_cast<*a simple type here*>(c);
You could obtain the latter, yes, though I don't see what advantage it
gives.

#include <ostream>

struct simple_type
{
typedef unsigned short number_type;

number_type m_n;

explicit simple_type( char c )
: m_n( static_cast< unsigned char >( c ) )
{
}
};

std::ostream &
operator<<( std::ostream & dest, const simple_type & s )
{
return dest << s.m_n;
}

--
Gennaro Prota
https://sourceforge.net/projects/breeze/
Apr 30 '07 #7
On 30 Apr 2007 07:07:41 -0700, Dancefire wrote:
>Currently, I have to use the
following loop to show each character as a number:

string test("\xba\xba" );
for(std::strin g::iterator iter = test.begin(); iter != test.end(); +
+iter)
{
cout << "0x" << hex << (unsigned short)((unsigne d char) *iter) <<
" ";
}

The *iter is char, not unsigned char. So, I have to use double casting
to do the job. If I use c-style function, I can easily specify "%x" in
the format string of printf() to print the char without any
unnecessary casting, it looks much straightforward .
BTW, where did you get that idea from? If you specify "%x" the
corresponding argument must have type unsigned int; otherwise you have
*undefined behavior*.

--
Gennaro Prota
https://sourceforge.net/projects/breeze/
Apr 30 '07 #8
Dancefire wrote:
....
Did I miss anything? What is the most directly way to use std::cout
output a char as a number?
No, you didn't miss anything. There may be slightly more elegant
solutions but this is what you get when the compiler picks your output
format by overloading the << operator.

To make it a little more palatable, this is one alternative.

unsigned OutAsUnsigned( char val )
{
return 0xff & unsigned( val );
}
cout << hex << "0x" << OutAsUnsigned( cc[0] )
<< 0x" << OutAsUnsigned( cc[1] );
Apr 30 '07 #9
And the above function still cannot output the number, it's will still
output the character, Unless I call another casting to cast the
unsigned char to unsigned short.

No. First the function performs no output, just a (double) conversion.
Secondly, the return type is unsigned int, not unsigned char. Try

std::cout << as_unsigned( c );
oops, yes you're right, the function return "unsigned" which is
"unsigned int", that makes it work. But, actually, it's still a double
casting of the char, one explicit casting in as_unsigned() function,
one implicit casting during the return of the function. After
optimization by compiler (eliminate the function call), the result
will be the same as the in place double casting.
It's not better than just double casting the char at the place

It's better than double casting "in place" for at least two reasons:
a) it gives a name to the operation you perform b) it encapsulates the
way you do it: should you later discover that the way you did it is
incorrect, you just have to fix it in one place.

And, of course, you should anyway use new-style casts.
Yes, you are right, encapsulate the operation as a function can make
the debug much easier.
I output it. which is provide at original post:
cout << " 0x" << hex << static_cast<uns igned
short>(static_c ast<unsigned char>(c));
But this form is not semantically correct,

You lost me here. Didn't you say in your original post that this gives
what you want?
The original solution in my first post:

cout << " 0x" << hex << (unsigned short)((unsigne d char)c);

It works, (I modified them to static_cast<>() way now), I'm currently
using this way, but I think this form is not elegant and might be not
necessary. I thought there may be a flag or something like "hex" in
STL can be set on cout, so I can directly cout << c, without any
(logically) unnecessary casting in my code.
I only want to output the 8-
bit unsigned integer, rather than 16-bit unsigned integer.

What's the difference on output if your unsigned int has at most 8
bits on?
no, no different for the output, just might not elegant in the code.
And I use 2
casting only for correct output the char as a number? Is there any
other way to do that? is there anything just like the printf("%x", c)
in cout, which means I set something, and then the output for char is
a number. Such as:
cout << " 0x" << hex << char_is_number << c;
or
cout << " 0x" << hex << static_cast<*a simple type here*>(c);

You could obtain the latter, yes, though I don't see what advantage it
gives.

#include <ostream>

struct simple_type
{
typedef unsigned short number_type;

number_type m_n;

explicit simple_type( char c )
: m_n( static_cast< unsigned char >( c ) )
{
}
};

std::ostream &
operator<<( std::ostream & dest, const simple_type & s )
{
return dest << s.m_n;
}

--
Gennaro Protahttps://sourceforge.net/projects/breeze/
Yes, I can get the latter form by this code, but I don't see the
advantage of it either, and it actually do the same thing above,
double casting, and just became a struct form.

So, in conclusion, there is no way to avoid the double casting if I
want std::cout output a char as a number, right?

Thank you.

May 1 '07 #10

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

Similar topics

6
2357
by: clilley | last post by:
The following code causes a segmentation fault on DEC Tru64: foo.cc (built into libFoo.so) //--------------------------- include <iostream> bool createFoo() { std::cout << "createFoo" << std::endl; }
6
3101
by: nish.parikh | last post by:
Hi, I am using std::cout to print a char pointer that is NULL. Subsequent calls to std::cout dont print anything. Is this the expected behavior? example: #include <iostream> int main( int argc, char *argv ) { char *q = 0; std::cout << q << "\n";
3
6662
by: Jim Langston | last post by:
I have a computer game that has no console. If I want to output something I push a string to the back of a std::vector<std::stringand that gets output and maintained. All is well and good, but what I would like to do is to be able to use ostream's power for this output. I could create my own ostream and check it every cycle or something, but then I would have to pass this ostream or make it global. What I would like to do is have...
8
3461
by: jean.daniel.michaud | last post by:
Hi all, Something I don't get. The code is: // snippet on #include <list> #include <iostream> int main()
1
10899
by: taiyang902 | last post by:
i program under linux ,and using kdevelop c/c++. the code follow, #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <iostream> #include <cstdlib> using namespace std;
5
2584
by: wongjoekmeu | last post by:
Dear All, I have written a small program to read in from console a user string. I wanted to be able to read in a string containing of all sorts of characters untill the user press enter. I have to use in my program the scanf function. The program works fine, but there is one exception. When I don't insert any input, but simply press enter, I want actually to pop up asking the user to enter a valid input. But it seems according to my...
0
216
by: acehreli | last post by:
On Jul 7, 9:56 am, Carsten Fuchs <CarstenFu...@T-Online.dewrote: One option is to leave cout to the others and maintain your own ostream which shares the same output buffer (but not formatting) with cout: #include <iostream> #include <iomanip> using namespace std;
11
6697
by: Adrian | last post by:
Is it possible to save a copy of cout the same way you can save a copy of stdout in C (I know C version is portable, but unix portable is good enough for me). I have to use a library which closes stdout on init because its used to mostly in background processes but I need it for an interactive process. Library cant be changed unfortunately. I tried the following but the C++ version doesn't work, I guess because it only shares the...
58
4808
by: Mark Casternoff | last post by:
I'm getting back into C++ after a long hiatus (they didn't have namespaces back then). I know this question is completely subjective, but I'd be interested in hearing which is the "better" style and what the pros and cons are (I'm using cout as example, but it really applies to any similar construct): 1) using std::cout;
0
7929
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8280
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6739
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
5882
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5441
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
3907
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2434
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1526
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1266
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.