473,695 Members | 2,502 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

print a byte number with cout

I have an array of char

for example:
char tag[] = {1, 'W', 0xFF, 0xFF};

I want to obtain:
01 57 FF FF

if I try with:

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

static const char tag[] = {1, 'W', 0xFF, 0xFF};

int main(void)
{
ios::fmtflags old = cout.flags();
for(int i = 0; i< 4; i++) cout << hex << uppercase << setw(2) <<
setfill('0') <<
(unsigned char)tag[i] << " ";
cout.flags(old) ;
cout<<endl;
return 0;
}
I obtain:
0 0W 0˙ 0˙

If I modify the cast from (unsigned char)tag[i] to (unsigned short)tag[i]

I obtain:
01 57 FFFF FFFF

I don't want to use printf, but with it could be simpler:
#include <stdio.h>

static const char tag[] = {1, 'W', 0xFF, 0xFF};

int main(void)
{
for(int i = 0; i< 4; i++) printf("%02hhX ",tag[i]);
printf("\n");
return 0;
}
so, how to print a byte numbe in hex format using cout?

thanks
--
Mastupristi?
Jul 23 '05 #1
4 14753
HI,

First you have to cast tag[i] to int;

for example

int val = tag[i];
cout << hex << setw(2) << setfill('0') << val << endl;

regards

Johan

"Mastuprist i" <cialdi_NO_SP@A M_gmail.com> schreef in bericht
news:2005022417 0131.000001f9.c ialdi_NO_SP@AM_ gmail.com...
I have an array of char

for example:
char tag[] = {1, 'W', 0xFF, 0xFF};

I want to obtain:
01 57 FF FF

if I try with:

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

static const char tag[] = {1, 'W', 0xFF, 0xFF};

int main(void)
{
ios::fmtflags old = cout.flags();
for(int i = 0; i< 4; i++) cout << hex << uppercase << setw(2) <<
setfill('0') <<
(unsigned char)tag[i] << " ";
cout.flags(old) ;
cout<<endl;
return 0;
}
I obtain:
0 0W 0˙ 0˙

If I modify the cast from (unsigned char)tag[i] to (unsigned short)tag[i]

I obtain:
01 57 FFFF FFFF

I don't want to use printf, but with it could be simpler:
#include <stdio.h>

static const char tag[] = {1, 'W', 0xFF, 0xFF};

int main(void)
{
for(int i = 0; i< 4; i++) printf("%02hhX ",tag[i]);
printf("\n");
return 0;
}
so, how to print a byte numbe in hex format using cout?

thanks
--
Mastupristi?
Jul 23 '05 #2
Johan wrote:
First you have to cast tag[i] to int;


For signed chars with negative values this actually does the wrong
thing: the sign is extended to fit the bigger integer type which
results in a value with all the higher bits being set. What the
original author has to do is to first cast the signed character to
an unsigned character and then to an appropriate integer type: when
casting to the unsigned character type, the bits remain unchanged
and for unsigned types there is no sign extension - obviously, since
they don't have a sign. That is, the code would look something like
this:

std::cout << int(static_cast <unsigned char>(tag[i]));

assuming the stream is setup appropriately to fit the desired
formatting.

BTW, note that you need to go through a similar procedure if you
want to use C's character classification function like 'isspace()':
these are only defined for unsigned character values but often the
type 'char' is signed (the standard makes not guarantee about the
signedness of 'char').
--
<mailto:di***** ******@yahoo.co m> <http://www.dietmar-kuehl.de/>
<http://www.contendix.c om> - Software Development & Consulting

Jul 23 '05 #3
Mastupristi wrote:
I have an array of char

for example:
char tag[] = {1, 'W', 0xFF, 0xFF};

I want to obtain:
01 57 FF FF

if I try with:

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

static const char tag[] = {1, 'W', 0xFF, 0xFF};
Change this to unsigned char. 0xFF is not a valid char on your system.
int main(void)
{
ios::fmtflags old = cout.flags();
for(int i = 0; i< 4; i++) cout << hex << uppercase << setw(2) <<
setfill('0') <<
(unsigned char)tag[i] << " ";
Change that to int(tag[i])

I obtain:
0 0W 0˙ 0˙

If I modify the cast from (unsigned char)tag[i] to (unsigned short)tag[i]
I obtain:
01 57 FFFF FFFF


Jul 23 '05 #4
On Thu, 24 Feb 2005 17:01:31 +0100, Mastupristi <cialdi_NO_SP@A M_gmail.com>
wrote:

[...]

static const char tag[] = {1, 'W', 0xFF, 0xFF};

int main(void)
{
ios::fmtflags old = cout.flags();
for(int i = 0; i< 4; i++) cout << hex << uppercase << setw(2) <<
setfill('0') <<
(unsigned char)tag[i] << " "; [...]
If I modify the cast from (unsigned char)tag[i] to (unsigned short)tag[i]

I obtain:
01 57 FFFF FFFF
This casts a signed char to an unsigned short, which results in the
undesired behaviour. The easiest way to fix this is to change tag[] to an
unsigned char array, but this may cause side-effects.

Another poster suggested a better method - cast to unsigned char, and cast
the result to an integer or short.

I don't want to use printf, but with it could be simpler:
#include <stdio.h>


It's best to use <cstdio> if you want to use printf() - it helps keep the
global mainspace free from clutter.
Jul 23 '05 #5

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

Similar topics

14
2906
by: Marcin Ciura | last post by:
Here is a pre-PEP about print that I wrote recently. Please let me know what is the community's opinion on it. Cheers, Marcin PEP: XXX Title: Print Without Intervening Space Version: $Revision: 0.0 $
5
3975
by: cybersangeeth | last post by:
Hi, I need to read 1KB each time from multiple files in a folder and pass it to a byte array in a struct to be sent through a socket. I'm a C++ newbie. I managed to read 1KB each time from one file and store it on to another file using the following code. Could anyone please let me know how i could go about reading from multiple files. Thanks in advance. typedef struct {
1
3601
by: iwongu | last post by:
Hi, I have a question about std::wcout and its underlying C functions. According to C99, a stream have an orientation type that is one of byte-oriented or wide-one, and it is determined by the first using C function on that stream. And the specific orientation functions should not be applied to the stream that have other orientation.
2
4372
by: DBuss | last post by:
OK, I'm reading a multicast socket. It attaches fine, reads fine, all of that. The problem is that while some of the data I get is normal text (ASCII String), some of it is Binary Integer. The binary data is how they send numbers (they call it "Big Endian"). I only know at run time whether a byte is going to be text or binary (one of the fields I decode tells me which the latter fields are). The code I have converts a single byte of...
6
3758
by: devoreband | last post by:
hey i wrote all my code but i need to print out only the even numbers so is there any predefined function i can use or what can structure i should be following? ........ 16 for(int r = 0; r < 10; r++) { 17 for(int c = 0; c < 10; c++) { 18 cout << setw(5) << setfill(' ') << r*c; 19 } // end for c 20 cout << endl;
4
4597
by: j_depp_99 | last post by:
Thanks to those guys who helped me out yesterday. I have one more problem; my print function for the queue program doesnt work and goes into an endless loop. Also I am unable to calculate the length of my queue. I started getting compilation errors when I included a length function. <code> template<class ItemType> void Queue<ItemType>::MakeEmpty() {
29
2958
by: Virtual_X | last post by:
As in IEEE754 double consist of sign bit 11 bits for exponent 52 bits for fraction i write this code to print double parts as it explained in ieee754 i want to know if the code contain any bug , i am still c++ beginner
3
1862
by: Hypnotik | last post by:
Hello everyone. This is a relatively simple program that is driving me crazy. The user enters how many verticies and how many edges. The program then asks where the edges are...in a 2D array. If the user enters a 1 (indicated there is an edge) that array element is set to 1. For some reason my print out is all wrong. It prints out to many elements, and incorrect values. Any help is appreciated, I think I'm just missing some minor thing....but...
8
2577
by: andrew.smith.cpp | last post by:
Hello how Can i get this kind of output? 1,2,3,5,8,13,21 i try it with loop but could print it. Thanks
0
9120
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8853
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8831
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
7667
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
6494
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
5841
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
4345
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...
0
4583
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
1978
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.