473,385 Members | 1,333 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,385 software developers and data experts.

printf for a char in hex - why all the F's?

I'm having a weird problem with printing bytes in hex format.

I have a bunch of print statements that are working okay, then using
the identical formatting later in my code I get some thing where the
formatting and type are ignored.

At one spot in my code I'm loading an array with random bytes

int i;
char byte_block[20];

for (i=0; i<20; i++)
byte_block[i] = (char) rand()

then elsewhere:

for (i=0; i<20; i++)
printf(" heres a byte: %2.2X \n", byte_block[i]);
rand() returns a random integer, but I'm casting it to a char, which
should give me a single byte
when I print out various elements of the array byte_block, I often get
a number much bigger than a byte (it's 4 bytes)

For some reason I get:

00 FFFFFFB3 77 FFFFFF82 FFFFFFAC 22 37 63 FFFFFFD6 74
77 FFFFFFBD FFFFFFED 09 30 FFFFFFC9 FFFFFFC4 FFFFFFE9 7C 61

(my extra cr/lfs)
Why are some prints nice 2 digit bytes and others have 6 F's? What am
I missing.
Elsewhere in my code I'm doing the same thing and get a nice string of
2digit bytes.

Even when I do this:

printf(" heres a byte: %2.2X \n", (char)byte_block[3]);
I get FFFFFF82. The format and the cast are being ignored??

Confused on a friday evening,

Ross
Nov 14 '05 #1
8 20078
scrodchunk wrote:
I'm having a weird problem with printing bytes in hex format.

I have a bunch of print statements that are working okay, then using
the identical formatting later in my code I get some thing where the
formatting and type are ignored.

At one spot in my code I'm loading an array with random bytes

int i;
char byte_block[20];

for (i=0; i<20; i++)
byte_block[i] = (char) rand()


Try declaring byte_block as unsigned char.

When by casting to char you truncate and just get
the lowest order byte, which can contain any value from
0x00..0xFF. A positive char can be 0x00..0x7F.
0x80..0xFF represents negative numbers. printf is
interpreting the %2.2X as a signed integer and dealing
with it as such.

Hope this helps.
Drew
Nov 14 '05 #2
scrodchunk wrote:
I'm having a weird problem with printing bytes in hex format.

I have a bunch of print statements that are working okay, then using
the identical formatting later in my code I get some thing where the
formatting and type are ignored.

At one spot in my code I'm loading an array with random bytes

int i;
char byte_block[20];

for (i=0; i<20; i++)
byte_block[i] = (char) rand()
Missing a semicolon, methinks.
then elsewhere:

for (i=0; i<20; i++)
printf(" heres a byte: %2.2X \n", byte_block[i]);
rand() returns a random integer, but I'm casting it to a char, which
should give me a single byte
when I print out various elements of the array byte_block, I often get
a number much bigger than a byte (it's 4 bytes)

For some reason I get:

00 FFFFFFB3 77 FFFFFF82 FFFFFFAC 22 37 63 FFFFFFD6 74
77 FFFFFFBD FFFFFFED 09 30 FFFFFFC9 FFFFFFC4 FFFFFFE9 7C 61

(my extra cr/lfs)
Why are some prints nice 2 digit bytes and others have 6 F's? What am
I missing.
Consider the 128's bit in each of the above numbers.
Does a pattern emerge?
Elsewhere in my code I'm doing the same thing and get a nice string of
2digit bytes.

Even when I do this:

printf(" heres a byte: %2.2X \n", (char)byte_block[3]);
I get FFFFFF82. The format and the cast are being ignored??

Confused on a friday evening,


The `char' type may be signed or unsigned, at the
implementation's discretion: some implementations make
it unsigned and consider the values as running from zero
to 255 (or higher; `char' may be wider than 8 bits), while
others make it signed and think of the values as running
from -127 (or lower) to 127 (or higher). The commonest
variations are -128 <= `char' <= 127 or 0 <= `char' <= 255.

Your implementation is probably of the former type.
Now, what happens to a `char' value when you pass it to
a function like printf(), where the parameter type is not
specified? It gets promoted, most likely to `int' (but to
`unsigned int' on some unusual machines). And if you take
a `char' whose value is -42, say, what `int' value do you
get after the promotion? And what are the high-order bits
of that `int' value?

I'm tempted to suggest you use `unsigned char', but
I really don't know what you're trying to do. In any case
you're using rand() in a less-than-wonderful way; see
Question 13.16 in the comp.lang.c Frequently Asked Questions
(FAQ) list

http://www.eskimo.com/~scs/C-faq/top.html

to learn what's wrong with your method, and what to do
about it.

--
Er*********@sun.com

Nov 14 '05 #3
Op 25 Jun 2004 14:58:08 -0700 schreef scrodchunk:

<snip>
char byte_block[20];

unsigned char byte_block[20];

In C a char usually is signed.
--
Coos
Nov 14 '05 #4
scrodchunk wrote:
I'm having a weird problem with printing bytes in hex format.

I have a bunch of print statements that are working okay, then using
the identical formatting later in my code I get some thing where the
formatting and type are ignored.

At one spot in my code I'm loading an array with random bytes

int i;
char byte_block[20];

for (i=0; i<20; i++)
byte_block[i] = (char) rand()

then elsewhere:

for (i=0; i<20; i++)
printf(" heres a byte: %2.2X \n", byte_block[i]);
rand() returns a random integer, but I'm casting it to a char, which
should give me a single byte
when I print out various elements of the array byte_block, I often get
a number much bigger than a byte (it's 4 bytes)

For some reason I get:

00 FFFFFFB3 77 FFFFFF82 FFFFFFAC 22 37 63 FFFFFFD6 74
77 FFFFFFBD FFFFFFED 09 30 FFFFFFC9 FFFFFFC4 FFFFFFE9 7C 61

(my extra cr/lfs)


Your chars appear to be signed. Note the added 'unsigned' below:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
int i;
unsigned char byte_block[20]; /* mha: added 'unsigned' */
for (i = 0; i < 20; i++)
byte_block[i] = (char) rand(); /* mha: added ';' */
for (i = 0; i < 20; i++)
printf(" heres a byte: %2.2X \n", byte_block[i]);
return 0;
}

Nov 14 '05 #5


scrodchunk wrote:
I'm having a weird problem with printing bytes in hex format.

I have a bunch of print statements that are working okay, then using
the identical formatting later in my code I get some thing where the
formatting and type are ignored.

At one spot in my code I'm loading an array with random bytes

int i;
char byte_block[20];

for (i=0; i<20; i++)
byte_block[i] = (char) rand()

then elsewhere:

for (i=0; i<20; i++)
printf(" heres a byte: %2.2X \n", byte_block[i]);
rand() returns a random integer, but I'm casting it to a char, which
should give me a single byte


There may be problems elsewhere, but there is a problem in the
assignment of return value of function rand, an int type, to a
char type. if the value returned by rand is too large to fit in
a type char, the result is unpredictable.

You can change the array to unsigned char type and assign a
value using the '%' operator,ie, byte_block[i] = rand()%256.
You will have assurance that the value will be in the range of
0 - 255.

Example:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void)
{
unsigned i;
unsigned char byte_block[20];

srand((unsigned)time(NULL));
for (i=0; i<20; i++)
byte_block[i] = rand()%256;
for (i=0; i<20; i++)
printf("A byte: (HEX) %2.2X (DECIMAL) %3u\n",
byte_block[i], byte_block[i]);
return 0;
}

--
Al Bowers
Tampa, Fl USA
mailto: xa******@myrapidsys.com (remove the x to send email)
http://www.geocities.com/abowers822/

Nov 14 '05 #6
sc********@hotmail.com (scrodchunk) typa:
[...]
int i;
char byte_block[20];

(in addition to others answers)
I like to typedef the char according to its actual use, and the
typedef or #define of the implementation. For example:
typedef unsigned char byte;/* memory examination */
typedef unsigned char uint8;/* calculations, assuming 8 bits wide */
char just for ... characters.
--
Pierre
Nov 14 '05 #7
sc********@hotmail.com (scrodchunk) wrote:
I'm having a weird problem with printing bytes in hex format.

char byte_block[20];
printf(" heres a byte: %2.2X \n", byte_block[i]);

For some reason I get:

00 FFFFFFB3 77 FFFFFF82 FFFFFFAC 22 37 63 FFFFFFD6 74
77 FFFFFFBD FFFFFFED 09 30 FFFFFFC9 FFFFFFC4 FFFFFFE9 7C 61

"%x" and "%X" are only for printing 'unsigned int' values.
Passing a signed int to them is undefined behaviour. There is no
format specifier for printing signed values as hex.

Because printf() is variadic, its prototype can't specify the
type for the other parameters. In this case the rules of C state
that chars get promoted to 'signed int' (see the standard for a
list of other promotions and exceptions to this rule),
this is necessary in order for the variadic function mechanism to
work safely.
So if your char was negative then printf will receive a negative int.
Finally, with '%X' it was expecting an unsigned int, so probably
what will happen is that it will try and interpret the bit pattern
of your negative int as an unsigned int. On 2's complement machines
this actually works, so you will get the same display as if you went:
printf("%x", (unsigned int) foo);

If you want to print a value between 0..255 , you would have to
cast your char to an unsigned char before passing it to printf.
(Strictly speaking, I think it should be cast to unsigned char and
then to unsigned int, but in practice you never have to do this.)
Nov 14 '05 #8
In <1j*****************************@40tude.net> Coos Haak <j.******@hccnet.nl> writes:
Op 25 Jun 2004 14:58:08 -0700 schreef scrodchunk:

<snip>
char byte_block[20];

unsigned char byte_block[20];

In C a char usually is signed.


Except when it isn't.

The point is that, in C, plain char *may* behave like signed char and,
to avoid this possibility affecting your code, you use unsigned char
when you actually want to play with bytes.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #9

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

Similar topics

11
by: Pontus F | last post by:
Hi I am learning C++ and I'm still trying to get a grip of pointers and other C/C++ concepts. I would appreciate if somebody could explain what's wrong with this code: ---begin code block--- ...
11
by: Grumble | last post by:
Hello, I have the following structure: struct foo { char *format; /* format string to be used with printf() */ int nparm; /* number of %d specifiers in the format string */ /* 0 <= nparm <=...
3
by: buzzdee | last post by:
hi, i just wanted to print out some unsigned long int values in hexadecimal, printing out one value works, but not byte by byte. anybody has a suggestinon what my problem is? this is my...
7
by: sunfiresg | last post by:
During an interview, I am asked to answer a question: Printf is a major formatted output function provided by the standard C library. Printf accepts a formatting string followed by a various...
9
by: | last post by:
void show( char *s, ...) is a function seemd like prinf code -------------- #include <stdio.h> #include <stdarg.h> void show( char *s, ...) { va_list stage;
12
by: baumann | last post by:
hi all, printf("%c",b) doesn't work properly. #include <stdio.h> int a , b; char d, e; char * p; float f; int main(int argc, char* argv) {
15
by: Michael B Allen | last post by:
I'm printing tables of structure members in a terminal and I would like to use printf with an arbitrary pointer so that the code is smaller and I don't need to switch over ever possible type. ...
8
by: manochavishal | last post by:
Hi, I have a structure MAX_ID is 5 /**Structure for Copies*/ typedef struct NodeVideoCopy * NodeVideoCopyPtr ; typedef struct NodeVideoCopy {
11
by: vectorizor | last post by:
Hi guys, My program deals with with lots of large matrices. To easily debug it, I would like to be able to dump them in files, so that I can easily import then in other software (think matlab,...
43
by: Jrdman | last post by:
someone has an idea on how the printf function is programmed ?
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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...

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.