Go Down

Topic: String constructor bug (Read 1 time) previous topic - next topic

slourette

The following code outputs "13" rather than "D"

Code: [Select]
unsigned long test = 13;
String thisString = String(test, HEX);
Serial.println(thisString);


The string constructors that take a base as the second argument do not appear to work as intended for unsigned long or unsigned int values.

gentoouser

#1
Jul 16, 2011, 02:19 am Last Edit: Jul 16, 2011, 04:39 am by gentoouser Reason: 1
You are right.  This is code from Arduino 0022
Code: [Select]
String::String( const unsigned long value, const int base )
{
 char buf[33];  
 ultoa(value, buf, 10);
 getBuffer( _length = strlen(buf) );
 if ( _buffer != NULL )
   strcpy( _buffer, buf );
}


Notice
Code: [Select]

ultoa(value, buf, 10);


Should be
Code: [Select]

ultoa(value, buf, base);

gentoouser

But to be honest, I don't think the String class should be constructible from integers anyway, especially since the constructors aren't declared as 'explicit'.

Code from WString.h
Code: [Select]

    String( const int, const int base=10);
    String( const unsigned int, const int base=10 );
    String( const long, const int base=10 );
    String( const unsigned long, const int base=10 );


This allows for implicit type conversion from an integer to a string:
Code: [Select]

String s;

// This can be confusing, making programmers
// think s is an integer. The integer 100 is converted
// to a String and then assigned to the variables s.
s = 100;

// The same thing happens with functions.
void foo(String s)
{
\\ ...
}

// The integer 100 is implicitly converted to a String.
foo(100);

// The function call foo(100) is the same as
foo(String(100));

paporas

Hello,

That was very helpful! I came across this bug today. So, is it possible to correct it? Is there a file a can change? Could you please explain the procedure?
Thanks

robtillaart

C:\Program Files (x86)\arduino-0022\hardware\arduino\cores\arduino\Wstring.cpp    line 91
Rob Tillaart

Nederlandse sectie - http://arduino.cc/forum/index.php/board,77.0.html -
(Please do not PM for private consultancy)

robtillaart

reported it at - http://code.google.com/p/arduino/issues/detail?id=577 -

Rob Tillaart

Nederlandse sectie - http://arduino.cc/forum/index.php/board,77.0.html -
(Please do not PM for private consultancy)

Go Up