Forum Discussion
Altera_Forum
Honored Contributor
15 years agoC CODE Integer as ASCII to printf string...HELP!!!
Hi all,
As like the title, now i have an unsigned integer that contain 4 ASCII code for a string: 0x41424344--------- my unsigned integer I would like to print the out "ABCD" where the corresponding ASCII code is store inside my unsigned integer. I have try printf("%s",integer_a); but some can be print some cannot, especially with integer that contain zero.7 Replies
- Altera_Forum
Honored Contributor
When using the standard C library functions (such as printf), all strings must end with a zero, or null terminator character. If there is a zero byte in your integer, only what is before that will be considered part of the string.
Trying to display an integer with the "%s" format will give somewhat unpredictable results depending on the endianness of the architecture and what happens to be in memory after the integer. You are probably better off converting the integer to individual bytes and using the "%c" format specifier or converting all your data to a proper string (character array with null terminator). - Altera_Forum
Honored Contributor
printf("%.4s", &integer_a) will print at most 4 characters, but you really need to print the characters separately (unless you know that int is 32bits (or rather 4 times the size of char), that you have 4 characters, and that they are in the right bytes of the int.
The NiosII is 'little endian' (the lowest address of a word is it least significant byte) so that x=0x414243; printf("<%.4s>", &x) will generate "<CBA>". On a 'big endian' system (eg sparc or ppc) the same code will generate "<>". Setting x=0x41424344 would give "<DCBA>" and "<ABCD>" respectively. - Altera_Forum
Honored Contributor
Hi Kevin,
I want to sent package data to UART.I can sent the data one by one but i can't sent package format.For example; 717932 49 48 48 32 48 10 Can i send these ASCII codes to UART? - Altera_Forum
Honored Contributor
Hi nightsjudge,
I have a same problem with you. Did you do it? or anyone have an idea? Thanks. - Altera_Forum
Honored Contributor
Use a cast.
unsigned int my_integer = 0x41424344; char * c = (char*)&my_integer; Then you can use stuff like this printf("%c%c%c%c", c[3], c[2], c[1], c[0]); - Altera_Forum
Honored Contributor
Thanks rbugalho.
i must send the package data to UART.For example WR REG 0 or i can write this with ASCII but when i tried to send some datas are sent ,some datas are not send.I sent the datas one by one . How can i send the package data to UART? Thanks again - Altera_Forum
Honored Contributor
It is generally safer to use arithmetic to get the byte values from an integer.
So something like:void print_val(unsigned int val) { unsigned char c; c = val; c = val >>= 8; c = val >>= 8; c = val >> 8; printf("%c%c%c%c", c, c, c, c); }