B
bwaichu
Now, I read the faq, and it suggests using sprintf. However,
I want to all ways know where the integer finishes in the string.
Basically, I want to:
nbr | other data
But the other data all ways has to start at the same place. I had
some problems using sprintf to accomplish this requirement. Maybe
I am overlooking something. But sprintf translates the nbr exactly
into
the string, so the nbr 123, would end up occupying:
p[0] = '1'
p[1] = '2'
p[2] = '3'
So as the number grew, the space taken grew.
To solve this, I went with the solution below. But this would require
me
to OR back the number later. Is there a better way to do this?
Note: I am using uint32_t to signify a 32 bit unsigned integer. This
is implementation
specific, but for the sake of this discussion, I need to know
the size
of the integer being assigned to buf ahead of time. I am also
ignoring
dynamically allocated arrays for this discussion as well.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int
main(void) {
int i;
uint32_t nbr;
unsigned char buf[4];
nbr = 0xffffffff;
memset(buf, 0, sizeof buf);
buf[0] = (unsigned char)(nbr >> 24) & 0xff;
buf[1] = (unsigned char)(nbr >> 16) & 0xff;
buf[2] = (unsigned char)(nbr >> 8) & 0xff;
buf[3] = (unsigned char) nbr & 0xff;
for(i = 0; i < 4; i++)
printf("%d\n", buf);
exit(EXIT_SUCCESS);
}
I want to all ways know where the integer finishes in the string.
Basically, I want to:
nbr | other data
But the other data all ways has to start at the same place. I had
some problems using sprintf to accomplish this requirement. Maybe
I am overlooking something. But sprintf translates the nbr exactly
into
the string, so the nbr 123, would end up occupying:
p[0] = '1'
p[1] = '2'
p[2] = '3'
So as the number grew, the space taken grew.
To solve this, I went with the solution below. But this would require
me
to OR back the number later. Is there a better way to do this?
Note: I am using uint32_t to signify a 32 bit unsigned integer. This
is implementation
specific, but for the sake of this discussion, I need to know
the size
of the integer being assigned to buf ahead of time. I am also
ignoring
dynamically allocated arrays for this discussion as well.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int
main(void) {
int i;
uint32_t nbr;
unsigned char buf[4];
nbr = 0xffffffff;
memset(buf, 0, sizeof buf);
buf[0] = (unsigned char)(nbr >> 24) & 0xff;
buf[1] = (unsigned char)(nbr >> 16) & 0xff;
buf[2] = (unsigned char)(nbr >> 8) & 0xff;
buf[3] = (unsigned char) nbr & 0xff;
for(i = 0; i < 4; i++)
printf("%d\n", buf);
exit(EXIT_SUCCESS);
}