|
|
View previous topic :: View next topic |
Author |
Message |
cap110874
Joined: 31 Aug 2011 Posts: 1
|
Trying to fprint an int16 with 18 characters |
Posted: Wed Aug 31, 2011 2:42 pm |
|
|
Hi Folks - Please bear with me if this sounds a bit stupid -
I am trying to print an int16 with 18 characters.
ie:
int16 PT_IR_pulse_pattern_up = 0b1110100100010110;
I want it to look exactly the same when it fprints to my rs232 terminal but I have tried nearly every combination of %x, %ld ect ect ect and it always comes out different.
This is what i am currently trying:
fprintf(COM_A, "%lx \r\n", PT_IR_pulse_pattern_up);
and in the RS232 terminal it is showing as:
e916
ANY wise words of advice as to where I am going wrong would be greatly appreciated |
|
|
newguy
Joined: 24 Jun 2004 Posts: 1907
|
|
Posted: Wed Aug 31, 2011 2:52 pm |
|
|
Code: | signed int8 i;
printf(COM_A, "0b");
for (i = 15; i >= 0; i--) {
if (bit_test(PT_IR_pulse_pattern_up, i)) {
printf(COM_A, "1");
}
else {
printf(COM_A, "0");
}
}
printf(COM_A, " \r\n"); |
Edit: Thanks TTelmah, bonehead mistake fixed.
Last edited by newguy on Thu Sep 01, 2011 7:26 am; edited 1 time in total |
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19504
|
|
Posted: Thu Sep 01, 2011 2:46 am |
|
|
Ongoing to this:
1) The key point is that the standard printf function does not provide a '%b' output, which is why you couldn't find a way of doing it directly. It is a rare output now, with hex being much more common, because of it's bulk.
2) Newguy's code shows a simple but quite efficient way of doing it, but as written, the 'wrong way round' - counter needs to go from 15 to 0, not 0 to 15.
3) A search online, will find dozens of other routes, varying in speed, and code size.
As an alternative, the internal function itoa (part of stdlib.h), can canvert a value to it's binary string representation directly.
Another 'natty' route, is a simple lookup table, based upon hex:
Code: |
char hex_bin[16][5] = {"0000","0001","0010","0011","0100","0101","0110","0111", \
"1000","1001","1010","1011","1100","1101","1110","1111"};
void ophex_bin(int8 digit) {
if (digit>'9') {
if (digit>'F') digit-=0x20;
digit-=55;
}
else digit-='0';
fprintf(COM_A,"%s",&hex_bin[digit][0]);
}
////........
int16 PT_IR_pulse_pattern_up = 0b1110100100010110;
fprintf(COM_A,"0b");
printf(ophex_bin,"%04lx",PT_IR_pulse_pattern_up);
fprintf(COM_A,"\n\r");
|
Which converts the individual hex digits, to four character text representations (adds the '0b' text as well).
There are about as many solutions to this, as days in a year!....
Best Wishes |
|
|
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
Powered by phpBB © 2001, 2005 phpBB Group
|