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 SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Copy integer into char buffer

Status
Not open for further replies.

TheObserver

Programmer
Mar 26, 2002
91
0
0
US
I have a need to copy an integer (up to three digits) into a char buffer. The resultant field in the char buffer needs to be zero padded (IE 001 if the int is less than 10, 010 if the int is less than 100, and 100 if the int is 100 or greater).

I realize I can probably do a memset to get the 0's into the memory locations. I am mainly just wondering how to get the int into the buffer. I've thought about memcpy, etc, but I just want to make sure that that's the right way to go.

Thanks for your time.
 
You know the number can't be more than 3 digits, so just asign with a cast like:
Code:
buffer[0] = (char)((x/100)+(int)'0');
x %= 100;
buffer[1] = (char)((x/10)+(int)'0');
x %= 10;
buffer[2] = (char)((x)+(int)'0');
 
Why not just use sprintf like:
Code:
  sprintf(buffer,"%03d",x);

Good luck.
 
> Or darn, I should have thought of that itsgsd.

Seems like the obvious is usually the most difficult to come up with.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top