3

I need to include a 3 digit ascii representation of message length number in the message header, but I am having difficulty trying to pad the number with leading '0' zeros in order to keep the number of 'length' digits needing to be appended always 3 even when the message length is only one or two digits long.

Addendum: The problem, more specifically, is how to left-pad a char array containing the number representation. I got as far as defining what and where, but I couldn't figure out how to shift the char[] contents right in order to insert the "0" at msglength[0]. (I tried using strcat, but that didn't work).

char msglength[4]          //(3 digits + nul)
for (int pad=1; pad<=3-strlen(msglength); pad++)
{
    // add a leading zero char to msglength, but that involves
    // somehow shifting all its contents to the right
}
  • if( value<10 ) Serial.print("0"); else if ( value<100 ) Serial.print("00"); Serial.print(value); – Gerben Mar 3 '16 at 9:57
  • You have to move the bytes starting from the last one: for (int i = strlen(msg); i >= 0; i--) msg[i+3] = msg[i];. Make sure your char array is big enough, at least strlen(msg) + 3 (padding) + 1 (null terminator). – Edgar Bonet Mar 3 '16 at 11:00
  • Yes, I understand I must move the existing array char digits plus null terminator to the right (top) of the msglength[4] array, but somehow I must also insert a '0' char into each vacated position. But my lack of programming knowledge can only come up with a solution which requires 2 for( loop passes, with a temporay value to hold the amount of steps used in the first 'right-shift' pass, in order to fill with the appropriate number of '0's from the left in a second pass. Is there a more elegent solution other than using 2 for( loops and a temp variable? – Electroguard Mar 3 '16 at 14:15
  • Two loops is perfectly fine here. I do not think you can make it an better. – Edgar Bonet Mar 3 '16 at 14:34
5

This is the kind of situation where printf() comes handy:

printf("%03d", number);

prints the number in the format you described. Alas, printf() is not part of the standard Arduino API. But you can have it, nonetheless, at least on AVR-based Arduinos, as it is provided by the avr-libc, which is always linked with all Arduino programs. Some setup is needed to tell avr-libc about where is its “standard output”. We can use the macro fdev_setup_stream() to tell it to just push the bytes through Serial.write():

static int Serial_write(char c, FILE *) {
    if (c == '\n') Serial.write('\r');  // convert LF -> CRLF
    return Serial.write(c);
}

static FILE mystdout;

void setup() {
    Serial.begin(9600);
    stdout = &mystdout;
    fdev_setup_stream(stdout, Serial_write, NULL, _FDEV_SETUP_WRITE);
}

void loop() {
    static int count;
    printf("%03d and counting...\n", count++);
    delay(500);
}

C.f. the manual of avr-libc's stdio.h for details.

Pros of this method:

  • printf() has plenty of options to control the formatting of your messages.
  • It's very standard C, understood by anyone having programmed in that language.

Cons:

  • This can make your compiled program bigger than it would be if sticking with the Arduino API.
  • It's not the “Arduino way”.
  • 1
    I think you mean to use sprintf. printf tries to go to an output stream automagically, sprintf uses a destination buffer, which could then be sent via Serial.write(). – bss36504 Mar 3 '16 at 15:26
  • @bss36504: I mean printf(). Read my answer. – Edgar Bonet Mar 3 '16 at 19:36
  • 1
    sprintf is also a solution, especially since OP did't ask to print the data on the serial port. – Overdrivr Mar 4 '16 at 8:20
3

One straightforward way to do this is to extract digits separately (using integer division and mod). For example, the hundreds digit of a positive or unsigned int x is (x/100)%10.

A sketch shown below uses the statement

  Serial << ' ' << b/100 << (b/10)%10 << b%10;

to print a space and three digits of a positive number, with leading zeroes. Here are the first 18 lines of output from the sketch:

 000 001 002 003 004 005 006 007 008 009 010 011 012 013 014 015
 016 017 018 019 020 021 022 023 024 025 026 027 028 029 030 031
 032 033 034 035 036 037 038 039 040 041 042 043 044 045 046 047
 048 049 050 051 052 053 054 055 056 057 058 059 060 061 062 063
 064 065 066 067 068 069 070 071 072 073 074 075 076 077 078 079
 080 081 082 083 084 085 086 087 088 089 090 091 092 093 094 095
 096 097 098 099 100 101 102 103 104 105 106 107 108 109 110 111
 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
 000 001 002 003 004 005 006 007 008 009 010 011 012 013 014 015
 016 017 018 019 020 021 022 023 024 025 026 027 028 029 030 031

Here is the sketch:

#include <Streaming.h>

//char b=0;    // char is signed; messy when hi bit is on
byte b=0;    // byte is unsigned, all ok
void setup() {
  Serial.begin(115200);
}

void loop() {
  // To emulate
  //    Serial << ' ' << setw(3) << setfill('0') << b;
  // or
  //    Serial << ' ' << b<100? '0': '' << b<10? '0': '' << b;
  // write (eg)
  Serial << ' ' << b/100 << (b/10)%10 << b%10;
  // or if b is an int instead of a byte, write
  //    Serial << ' ' << (b/100)%10 << (b/10)%10 << b%10;

  ++b;
  if (b%16 == 0) Serial.println();
  delay(17);
}

The code shown above uses Streaming.h, a contributed library that adds some “syntactic sugar” to Arduino C. That is, at compile time it converts C++-like << Serial stream operators to Serial.print statements, without increasing code size. If you don't have Streaming.h installed, either install it via Streaming5.zip from arduiniana.org or manually translate the Serial << ... statement to Serial.print statements.

Note, if the Streaming.h library supported setw() and setfill(), they could be used to set field width and fill character. (See comments in sketch.) However, the current implementation merely translates the stream insertion operator << form into print() form. It supports four base-conversion specifiers, _HEX, _DEC, _OCT, and _BIN; a _FLOAT function with number of decimal places specified; and endl. Some _FILL functions are suggested at the Arduiniana.org link.

2

There is always brute force.

char* itob(int val, char* buf, size_t n)
{
  char* bp = buf + n;
  do {
    *--bp = (val % 10) + '0';
    val = val / 10;
  } while (bp != buf);
  return (buf);
}

void setup()
{
  Serial.begin(9600);
  while (!Serial);

  const int BUF_MAX = 3;
  char buf[BUF_MAX];

  Serial.write(itob(42, buf, BUF_MAX));
  Serial.println();
}

void loop()
{
}

Please observe that the buffer is not null-terminated, therefore the Serial.write().

Several possible optimizations from the simple solution such as detect when the value is zero and short-cut.

Cheers!

0

Thank you all for your suggestions. This is what I came up with, which seems to work ok.

char lengthstr[4]="7";  
Serial.print("lengthstr='"); Serial.print(lengthstr); Serial.println("'");
int maxsize=sizeof(lengthstr);  // size of lengthstr array
int steps=strlen(lengthstr)+1;  // number of chars to be moved
int hop=maxsize-steps;          // number of steps to be jumped over each move
if((steps>1)&&(maxsize>steps)) {  
   for (int pos=steps; pos >= 0; pos--) {
      lengthstr[pos+hop] = lengthstr[pos];
      lengthstr[pos]='0';
   }
}
Serial.print("lengthstr='"); Serial.print(lengthstr); Serial.println("'");
  • Two problems here: 1) On the first iteration of the for() loop, you are writing beyond the end of the lengthstr array. This is called memory corruption and can be a very nasty bug. The loop should start at pos=steps-1. 2) Assuming you fix that previous bug, the code will work if lengthstr is of size 4, but not if it's any bigger. Your initial two-loop idea was cleaner and would work at any size. – Edgar Bonet Mar 4 '16 at 9:04
  • Thanks Edgar, I very much appreciate your help and advice, so I will redo using 2 loops, which is easier to get my head around anyway. – Electroguard Mar 4 '16 at 11:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.