printf in C#

I’ve been wondering about making DANSE open-source for a while now (after all if anyone else wants to start using it seriously they will need the source code), but up until recently (well, yesterday) I’ve had a problem: DANSE uses a version of printf written in C# by Richard Prinz which is only available under the Code Project Open License, and this does not allow me to release the code under any other license. I can’t use the CPOL since there is other code also in DANSE released under the GPL.

I can’t use the built-in printf since I want to target Silverlight as well, and I can’t just use the C# print routines since the students taking the module where this software is used haven’t learned C#, all they know is C.

So I figured… how hard can it be to write my own version of printf? Perhaps not implementing all the features, but at least being good enough for my purposes here?

Turns out it’s not that hard, only took a couple of hours. Not very well tested yet, but if anyone else would like to give the following a spin and let me know how they get on, I’d be very interested.

internal enum eTStype { _int, _float, _exponential, _string, _char, _pointer, _hex, _octal, _gtype, _error }
internal class TS
internal int start; internal int end; internal int width; internal int precision; internal eTStype type;
internal TS(int A, int B, int C, int D, eTStype what)
{ start = A; end = B; width = C; precision = D; type = what; }

internal static string sprintf(string format, params Object[] parameters)
// Starts from a copy of the string format, then replaces the type specifiers.
string result = String.Copy(format);

// Keep a list of the type-specifiers as I go through...
List myTS = new List();

// The first type specifier will start with a % which is not preceeded by
// an escape character '\', include an option precision field (".X")
// and then a length and specifier, both of which are ignored to be
// friendly. The specifier is assumed to end at the first occurrance
// of any one of the following specifiers: i, d, u, o, x, X, f, F, e, E,
// g, G, c, s, or p. (C# knows what these variables are.)

// Go through the format string, counting how many type specifiers there
// are, and making a note of what they are:
for (int loop = 0; loop < format.Length; loop++) { if (format[loop] == '%' && (loop == 0 || format[loop - 1] != '\\')) { // Found the start of a format string. int startTS = loop; int precision = 0; int width = 0; Boolean precisionValid = false; eTStype what = eTStype._error; // Now I need to find the end of it and work out what it is: while (loop < format.Length && what == eTStype._error) { char c = format[loop]; if (c == '.') precisionValid = true; if (c == '0' || c == '1' || c == '2' || c == '3' || c == '4' || c == '5' || c == '6' || c == '7' || c == '8' || c == '9') { string TryThis = format[loop].ToString(); int whatIsThis = 0; int.TryParse(TryThis, out whatIsThis); if (precisionValid == true) precision = precision * 10 + whatIsThis; else width = width * 10 + whatIsThis; } if (c == 'i' || c == 'd' || c == 'u') what = eTStype._int; else if (c == 'o') what = eTStype._octal; else if (c == 'x' || c == 'X') what = eTStype._hex; else if (c == 'f' || c == 'F') what = eTStype._float; else if (c == 'e' || c == 'E') what = eTStype._exponential; else if (c == 'g' || c == 'G') what = eTStype._gtype; else if (c == 'c') what = eTStype._char; else if (c == 's') what = eTStype._string; else if (c == 'p') what = eTStype._pointer; loop++; } if (what != eTStype._error) { // Must have found the end of a format string, so add this to the list: if (precisionValid == false) precision = -1; TS ts = new TS(startTS, loop, width, precision, what); myTS.Add(ts); } } } // Right - now just go through and make a new string from the // non-type specifier parts of the format string, and the // replacements for the type-specifiers from the parameters list: StringBuilder sb = new StringBuilder(format.Length + 20 * myTS.Count); int lastFinishes = 0; for (int loop = 0; loop < myTS.Count; loop++) { int includeUpToHere = myTS[loop].start; sb.Append(format.Substring(lastFinishes, includeUpToHere - lastFinishes)); if (parameters.Length > loop) sb.Append(makeString(myTS[loop], parameters[loop]));
else sb.Append(" ERROR - Insufficient Parameters ");
lastFinishes = myTS[loop].end;
// Then add on the bit after all type specifiers:
sb.Append(format.Substring(lastFinishes, format.Length - lastFinishes));

return sb.ToString();
static private string makeString(TS ts, Object parameter)
if (ts.type == eTStype._error) return "*Error: Unrecognised type specifier*";

// For pointers, characters and strings all that's required is:
string q = parameter.ToString();

// Then if this is an integer, there are some special cases to include the
// precision, and deal with hex and octal numbers:
if (ts.type == eTStype._int)
long d;
if (long.TryParse(q, out d))
int prec = ts.precision;
if (ts.type == eTStype._hex)
q = d.ToString("X" + ((prec < 0) ? "" : ts.precision.ToString())); } else if (ts.type == eTStype._octal) { // Precision not implemented for octal yet. Does anyone care? string qq = Convert.ToString(d, 8); } else { q = d.ToString("D" + ((prec < 0) ? "" : ts.precision.ToString())); } } else { q = "*Error: Unrecognised type specifier*"; } } if (ts.type == eTStype._exponential || ts.type == eTStype._float || ts.type == eTStype._gtype) { char s = ts.type == eTStype._exponential ? 'e' : ts.type == eTStype._float ? 'f' : 'g'; double d; int prec = ts.precision; if (double.TryParse(q, out d)) q = d.ToString(s + ((prec < 0) ? "" : ts.precision.ToString())); else q = "*Error: Unrecognised type specifier*"; } // Then pad (or truncate) to fit the width required: if (ts.width > 0)
while (q.Length < ts.width) q = " " + q; if (q.Length > ts.width) return q.Substring(0, ts.width);
return q;
return q;

Posted in Uncategorized | Comments Off on printf in C#

Another reminder for me… ILMergeGUI

I’ve just updated the Audio Network Analyser program with a few bug-fixes and some additional features. For example there is now a new heuristic algorithm to try and automatically correct for phase measurements 180 degrees out – I’m still not sure why this happens, but at least the program tries to do something sensible to fix it when it does (it you suspect the corrections are getting things wrong, you can turn them off by checking the “Resonant Circuit” checkbox).

However, the big change is that you no longer have to download a zip file with the dll and the exe files separate, you can just download one assembly with everything in it. Having tried (and failed) a few times to get this to work, I finally found a method that worked for me: the ILMergeGUI program from

Many thanks to all of the developers of that rather useful little tool.

Posted in Uncategorized | Comments Off on Another reminder for me… ILMergeGUI

And another reason to stop writing the book…

…is that with so many more complex demos being written, and a few more in the pipeline, I find I need to spend quite a bit of time maintaining the ones that are here; and some video instructions and “demos of the demos” are long overdue, and these take a lot of time to produce too.

For example, there is a credible report of the Karnaugh Maps demo producing the wrong result (though so far I have been unable to reproduce this myself), and I wanted to add some more components into the Analogue and Digital demos.

Also, as soon as time allows, I want to give the dot42 Android environment a run as well, and see how hard it would be to convert some of these things to Android apps – that could vastly increase the number of people using them, as my students could use a mobile version of the quiz on their phones, for example.

However, the point of this blog post is to highlight that I’ve updated the Analogue simulator demos with a few bug-fixes and new features. Probably the most noticeable is the introduction of two new components: a voltage adder/subtractor, and a gain block. With these it’s possible to build an op-amp of any open-loop gain and unity-gain bandwidth (although in this case the heuristic algorithms that stop op-amps settling at an unstable operating point don’t work – take care when using positive feedback).

Posted in Uncategorized | Comments Off on And another reason to stop writing the book…

Couple more chapters, and a decision

OK, time for some stock-taking. When I first started this site, I was teaching communications theory full-time, and thought I’d be able to develop the content for this site in parallel with the work I was doing for my job anyway. However, a couple of years ago I changed job, and I’m only teaching two communications courses now, and it looks like I’ll be giving up one of those in the near future.

So I think it’s time to admit defeat on the idea of the book; I doubt there will ever be a complete book now. What I will do is try and complete the chapters I’ve started already, and get on with more of the demos = which are more fun to write, and certainly more useful to myself in my new job.

There are a couple of new chapters up now: one on the Wiener filter, and one on signal transforms. There will be a few more coming as well, one on the equivalent baseband representation, and one on noise and intermodulation products in receivers and perhaps a couple on the mobile radio channel. These are the subjects I found it hardest to get the hang of when I started, so I think perhaps they might be the ones most useful for others as well.

However, unless I get some requests, I don’t think I’ll start any new chapters now, certainly not on material that other authors have covered much better than I can. It just doesn’t seem to be worth doing, and my work interests have moved on somewhat.

Posted in Uncategorized | Comments Off on Couple more chapters, and a decision

Playing games with circuit theory?

So, I’ve been given this new module to teach next year: a basic introduction to electronics for those with little background in the subject. One of the books I’ve been reading recently (“Why Don’t Students Like School?” by Daniel T. Willingham) has confirmed what I’ve read elsewhere: that’s it almost impossible to acquire a new skill without a lot of practice.

On the other hand, just repetition of endless examples is rather boring; students don’t have much incentive to do it in a higher education environment where they don’t have to hand in regular homework every week; and having come to university and now consider themselves paying customers, this sort of exercise may not be what they are expecting or willing to engage in.

In any case, I don’t really want to write a lot of examples, and I certainly can’t mark hundreds of papers every week, and really why should students really engage with what can be a bit of a tedious exercise anyway?

So… perhaps time to try and experiment. The circuit theory game. Something that can be automatically marked, but something that will hopefully engage students by giving them scores not just at the end, but as you go. Throw in some elements of game, and with any luck the students will get engaged. Rough idea: they get a certain number of marks for getting a certain score in the game: the greater the score, the more marks. And to get marks you have to progress through the levels, solving problems against the clock.

There’s a very early prototype of the program available now – I’d welcome comments. What could make this more engaging? Is the scoring system sensible? Should the levels automatically increase after a certain number of questions, or should this be left up to the user – the higher the level the more points you get. Your best score for twenty questions gives you a mark – and you can make as many attempts as you like (after all, I’m trying to encourage practice here).

Try it out at

Oh by the way, I got a little bored going between typing on the keyboard and getting out my calculator to work out the sums, so I built a simple calculator into the program. Just type an expression like “3 / (82e3 + 100e3) + 4” into the answer box, and it should work out the expression for you.

There are still a few bugs in it, but it should give you the idea anyway. All comments welcome: will it work? How could it be improved?

Posted in Uncategorized | 3 Comments

New routeing demo just arrived

Just put up another demo, this one for routeing and Bellman-Ford. It doesn’t implement any actual protocols, it’s just there to demonstrate the operation of the Bellman-Ford algorithm. The first version of this was actually one of the first demos I wrote, back in the VB6 days; but since I don’t teach Bellman-Ford any more I’ve only just got round to converting it to Silverlight. The incentive was to demonstrate multicast routeing using reverse-path forwarding (which I do teach), and to do that I needed to get Bellman-Ford working.

It was rather a nice demo to write this one. It’s the sort of thing that OOP lends itself to really well, and I’ve had a few worries recently, and it’s good to be able to totally lose myself in something; writing software has always done that for me: been a bit of an escape from daily life.

I’ve not used this one myself in a class yet, so there might be (well, to be honest there almost certainly are) some bugs left in it; so please let me know if you find anything.

Having got the packets size, shape and movement all sorted out, it shouldn’t be hard to adapt this one to do bridging the spanning tree. That might be the obvious next thing to try; although since I don’t teach spanning tree at all these days I don’t have much incentive for that one. On the other hand, I can’t think of anything better to do.

Maybe I should take a break from demos and get on with the book chapters instead… so far I’m getting slightly more feedback about these than about the demos.

Posted in Uncategorized | Comments Off on New routeing demo just arrived

New “Flow Control” demo just up

Next new demo just put on-line: flow control. This one draws diagrams of the traces of packets going across links (with and without a router) using software flow control, stop-and-wait flow control, go-back-N flow control and such like.

Now available here:

I’ve just used this for the first time myself in the IET Satellite Summer School, so I thought I should add it up here in case anyone there was looking for it. Otherwise I think I would have left it a little bit longer to do some more testing. I was finding bugs and odd behaviour right up to the morning before the presentation, so it’s likely there are a few bugs left in there.

If anyone suspects it of doing something odd please let me know; equally if anyone is planning to use this in a lecture themselves, I’d suggest they run through what they’re planning to show a few times first, just to check the demo does what they expect.

Next thing… well, I’ve been reminded recently that some of the more basic electronics chapter of the book might be useful to put up, so I might get back to those. Otherwise the next demo is likely to be one about routeing: there was an old VB6 routeing demo, but I really want something that can demonstrate multicast routeing schemes. Hopefully since I’ve done something similar before it won’t take too much time.

Posted in Uncategorized | Comments Off on New “Flow Control” demo just up

The audio network analyser is now here

Latest program ready for release isn’t a demo in the usual sense; it’s not designed to be used in lectures and talks, it’s designed for use in the lab.

Our students spend some of their first term here building an external audio interface based around the TI PCM2902 chip, and some of their second term taking a lot of readings of the frequency and phase responses of reactive networks. The former task is quite interesting and engaging, the latter task is somewhat tedious. So – why not use the external audio interface to build a network analyser capable of measuring the frequency and phase response of a passive network?

All you would need is a bit of software, and writing software is more fun than most of my other tasks, so that’s what I’ve spent some of the summer doing. It’s finally ready for release, and can be downloaded from here: Audio Network Analyser Program.

It was designed for use with the USB audio interfaces the students build here, which use default Windows drivers. Under Windows 7 these don’t always put the system into the right mode – hence the initial information screen that comes up at the start of the program. The software should work with other modems and operating systems, but the input levels might need adjusting, and I’ve not tested it.

Playing around should give you the idea of how it works: the only non-obvious points might be:

  • If you tick the “Accept Invalid” checkbox, the system will use values that might not be valid due to either saturation or very low input levels. Otherwise, these readings will be ignored.
  • If a reading comes in wrong (occasionally the phase is reported as being 90 degrees wrong, I’m still trying to track this one down), double-clicking on a reading will remove it. You can then replace it by moving the slider to the required frequency, and press “Single” to take a single reading at that frequency.
  • Click on the Bode plot to place a new pole. Double click on a pole to turn it into a zero (and vice versa). Drag it off the plot to remove it. Alternatively, poles and zeros can be entered using the windows that pop-up when pressing the “Poles” or “Zeros” buttons.

Next feature to add will be the additional of complex poles so we can use it with the resonant circuits the students come across later in their degree programmes.

If anyone wants to try it out, please let me know any successes/failures/comments.

Posted in Uncategorized | Comments Off on The audio network analyser is now here

Some thoughts about exam revision and technique

A few years ago I wrote some advice for how to prepare and do exams for my students here, and I put them up on the internal web-site. A couple of people wrote from other institutions and asked if they could use them, so I said I’d put them up here so they would be more generally visible.

I then foolishly made it rather difficult for anyone to find them. Google has managed it, and you can find them under the “Book” menu (but you have to know they are there). For anyone else interested, they are here:

All comments and additions very welcome.

Posted in Uncategorized | Comments Off on Some thoughts about exam revision and technique

Feeling unwelcome at the Times Higher Education

The Times Higher Education. Undoubtedly the newspaper of my profession. And yet I’m now feeling rather unwelcome there.

Why? Well as regular readers (!) will have noticed, I’ve recently joined Twitter. Looking around at suitable people to follow, I found THE were regular tweeters, and decided to follow them. A lot of their tweets led to interesting articles on their website, and in order to read those I had to register on their site.

One of the pieces of information they collect during the registration process is job title. So I started looking down the list. “Academic” was not there. I looked on, past “Lecturer” and “Professor”, past “Reader” and “Researcher” (both Junior and Senior), past “Student” and then onto “Vice-Chancellor / Principal”.

“Hang on”, I thought. “What about the teachers?” Not there. You cannot register with the Times Higher Education as a “Teaching Fellow”, “Teaching Assistant” or “Teacher”. I had to register as “Other”.

It would appear that anyone with research as part of their job description (including “Research Administrators”, but notably no other administrators) are welcome to register using their real job titles. But anyone whose job starts with the letters ‘T’, ‘E’, ‘A’, ‘C’ and ‘H’ isn’t.

Why does the Times Higher not acknowledge the teaching specialists on the registration form? Could it be that they are, in fact, very rare, and most universities don’t employ them? In which case I’m very lucky to be employed here: in the department where I work there are more Teaching Fellows than Readers (and Lecturers only outnumber us by one).

If it’s not rarity, then I’m really struggling to think of a good reason, especially in these days when teaching quality seems to be becoming a real issue for universities. Someone more paranoid than me could even interpret this as yet another symptom of the traditional priority given to research activities.

BTW I did contact THE about this, and received a polite reply saying that they would bear this issue in mind when they next review the registration process. I’ll keep an eye out to see if anything happens.

Posted in Uncategorized | Comments Off on Feeling unwelcome at the Times Higher Education