![]() |
| | #1 |
| Registered User Join Date: Mar 2009
Posts: 4
| How to make itoa write the left zeros? I' trying to convert hexadecimal to binary, I'm using itoa and it seems to be working right, the problem is that it skip every zero at the left of the first one. Is there any way to force it to write this zeros? Code:
printf("%s ", itoa(str2 , str, 2) );
if str2="2" it prints only 10, I would like to print 0010 Thanks in advance |
| pajaro is offline | |
| | #2 |
| Registered User Join Date: Jan 2009
Posts: 26
| check the strlen() of received string and do the loop: for (i = 1; i <= 4 - strlen(itoa(...))); i++) printf("0"); |
| baccardi is offline | |
| | #3 |
| Algorithm Dissector Join Date: Dec 2005 Location: New Zealand
Posts: 2,476
| I think that the most efficient option in this case would be to not use itoa. It's not designed for what you want. Just declare a mask variable, make a loop that loops until the mask is zero, shifting it right each time, then test each bit of the input by anding it with the mask. Code: char buffer[16], len= 0;
for (int mask = 0x8; mask > 0; mask >>= 1)
{
buffer[len++] = (input & mask) ? '1' : '0';
}
buffer[len++] = '\0';
__________________ My homepage Advice: Take only as directed - If symptoms persist, please see your debugger |
| iMalc is offline | |
| | #4 |
| CSharpener Join Date: Oct 2006
Posts: 5,242
| better to make mask unsigned int
__________________ If I have eight hours for cutting wood, I spend six sharpening my axe. |
| vart is offline | |
| | #5 |
| Registered User Join Date: Mar 2009
Posts: 16
| sorry to both you, but i just joined the fourm and i am wondering how do i start a new post because i have a question with my code? thanks |
| CaliJoe is offline | |
| | #6 |
| Registered User Join Date: Jun 2008
Posts: 1,134
| Press new thread where the rest questions are. Search and you will see it |
| C_ntua is offline | |
![]() |
| Tags |
| binary, fill zeros, itoa |
| Thread Tools | |
| Display Modes | |
|
Similar Threads | ||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| "Cannot make pipe" | crepincdotcom | C Programming | 5 | 08-16-2004 12:43 PM |
| Request for comments | Prelude | A Brief History of Cprogramming.com | 15 | 01-02-2004 10:33 AM |
| Question about atheists | gcn_zelda | A Brief History of Cprogramming.com | 160 | 08-11-2003 11:50 AM |
| How can we write a C shell script to make Dirs | Unregistered | Linux Programming | 3 | 04-27-2002 10:27 PM |
| write then make R-O | confusedcoder | C++ Programming | 1 | 01-25-2002 07:53 AM |