I made the size of "val" uint32_t so it would take any integer size (besides long long), is there a way to make val accept any integer size so I could calculate "numBits" from "sizeof(val) * 8"? I tried "size_t val" but no workum.
Here's a working sketch:
the compiler will allocate the number of bytes that are necessary for the type of variable you declare. so here you said it's a 32 bit unsigned integral and thus in the function you will always see 4 bytes, regardless if you called the function by passing a uint16_t or uint8_t or uint32_t. The compiler will have automatically cast before the call that value into a uint32_t.
What you could check is if the most significant bytes are empty, and second guess what's really necessary to print out
The other option is to use the fact that you can have multiple functions with the same name if the parameters are different (it's called the signature of the function). for example if you run this
so to your programming needs you only need to remember the f1() function but in real code, based on the type you pass in parameter, different code is being called.
outsider:
I made the size of "val" uint32_t so it would take any integer size (besides long long), is there a way to make val accept any integer size so I could calculate "numBits" from "sizeof(val) * 8"? I tried "size_t val" but no workum.
if you use a template you don't need to pass the size:
template <class T> void printBits(T &value)
{
Serial.print(F("0b"));
for (size_t i = 0; i < sizeof(T) * 8; i++)
{
T mask = 1;
Serial.print((value & (mask << sizeof(value) * 8-i-1)) ? "1" : "0");
}
Serial.println();
};
void setup()
{
Serial.begin(9600);
uint8_t num = 0xF0;
uint64_t val = 0xFF00FF00FF00FF00;
printBits(num);
printBits(val);
}
void loop()
{
}
Alright guys, got something to work, kind of klunky and could do with some refinement, (how to put all in 1 "box"?) but works so far, (acid testing now).
TNX all and K++ all around for helpful suggestions.
@bulldogL:
I'm intrigued by your template sketch, but I get:
Arduino: 1.6.5 (Linux), Board: "Arduino Pro or Pro Mini, ATmega328 (5V, 16 MHz)"
Build options changed, rebuilding all
sketch_dec22d:2: error: variable or field 'printBits' declared void
sketch_dec22d:2: error: 'T' was not declared in this scope
sketch_dec22d:2: error: 'value' was not declared in this scope
variable or field 'printBits' declared void
This report would have more information with
"Show verbose output during compilation"
enabled in File > Preferences.
Templates and classes are still over the Moon for me. Do you want to see the verbose version?