Firstly I must apologise if the answer to this is elsewhere within the forum, I have searched and googled most of my monthly data allowance away trying to find the answer.
Is there a way to convert a four digit DEC value to 16 bit BIN ?
Example
As Decimal: 1234
As Binary: 0000010011010010
sterretje:
Please rephrase. Are the values numbers or text.
Hi they are numbers as in the example.
I think I may have found the solution, I am just running it over and over and checking the results.
void setup()
{
Serial.begin(9600);
}
void loop()
{
int myNum = 4321;
int zeros = String(myNum,BIN).length();//This will check for the length of myNum in binary.
String myStr;
for (int i=0; i < 16 - zeros; i++) {//This will add zero to string as need
myStr = myStr + "0";
}
myStr = myStr + String(myNum,BIN);
Serial.println(myStr);
delay(1000);
}
Every time you add a char, the String copies itself with the added char then deletes the old copy leaving a hole in the heap. As that keeps happening, RAM gets wasted. An Uno or Nano only has 2048 bytes RAM for heap and stack.
With C strings you set up RAM enough to hold the longest text you will put in there + 1 byte for a terminating zero.
A char array with ASCII text values ending with a zero is what a C string is.
You can learn the functions in string.h but you can also manipulate C string text as char values in an array, which is all those functions do.
Assigning the number to an unsigned integer might achieve what you want.
There are functions for parsing individual bits out of a number. see: bit() etc.
The documentation for such functions is unfortunately of such a lamentable state that it is not clear what datatypes these can take.