Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Help!

Status
Not open for further replies.

davegibelli

Programmer
Nov 21, 2007
3
GB
I am trying to use printf to output an unsigned integer from a array of bytes but I cannot figure out how?

e.g.
char ptr[4]={0x00, 0x00, 0x00, 0xff);

printf("%u",*ptr);

but I cannot get the answer 255 :(
 
Code:
printf ("%u", (unsigned int)*ptr);
*ptr just gives you a char
(unsigned int)*ptr takes however many bytes an unsigned int takes and puts it into a char. Note that if you do this on a 16 bit machine, it will only take the first 2 bytes. If you do it on a 64 bit machine, it may take 4 or you might get a crash if it takes 8.
 
I still get the answer 0 instead of 255, I am using a 32bit machine...
 
Sorry it should have been
Code:
printf ("%u", (unsigned int)ptr);
 
Nope, that gives a different number each time the prog is run!
 
What does the program look like? There may be a bug somewhere else.
 
1. You would need to cast the pointer to an unsigned int pointer, then dereference it.
[tt]printf ("%u", *((unsigned int*)ptr) );[/tt]

2. This is a really bad idea, as int probably has stricter alignment requirements than char. It may work for you, but then again you may just get a "bus error".

3. If you want 255 from 00 00 00 FF, then you would need to be on a big endian machine. Consider FF 00 00 00 if you get a consistently large number like 4278190080.


--
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
 
If (and only if;) ptr is an array, you may use this awkward (but portable;) construct. See also Salem's notes about little/big-endian(s)...
Code:
#define Min(x,y) ((x)<(y)?(x):(y))
unsigned junk = 0;
...
printf("%u\n",
  (memcpy(&u,ptr,Min(sizeof junk,sizeof ptr)),u)
);
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top