I have an array
int before[] = {B0100, B1000, B0001, B0010};
I don't want it to be printed like this:
B0100
B1000
B0001
B0010
but like this
0 1 0 0
1 0 0 0
0 0 0 1
0 0 1 0
I am out of ideas. Thanks in advance.
I have an array
int before[] = {B0100, B1000, B0001, B0010};
I don't want it to be printed like this:
B0100
B1000
B0001
B0010
but like this
0 1 0 0
1 0 0 0
0 0 0 1
0 0 1 0
I am out of ideas. Thanks in advance.
looks like school work
show us at least what you tried.. It's not difficult using a couple for loop and bitRead()
here is an idea to explore
int before[] = {B0100, B1000, B0001, B0010};
void printBinary(int a[], size_t arraySize, byte nbBits) {
for (size_t i = 0; i < arraySize; i++) {
for (int b = nbBits - 1; b >= 0; --b) {
// print something smart here using bitRead()
// print something smart if b is not null
}
Serial.println();
}
}
void setup() {
Serial.begin(115200);
printBinary(before, sizeof before / sizeof * before, 4);
}
void loop() {}
int before[] = {B0100, B1000, B0001, B0010};
void setup()
{
Serial.begin(115200);
for (int row = 0; row < 4; row++)
{
for (int bit = 3 ; bit >= 0 ; bit--)
{
Serial.print(bitRead(before[row], bit));
Serial.print(" ");
}
Serial.println();
}
}
void loop()
{
}
Why are you wasting memory ny storing 4 bit values in a 16 bit in array ?
Because I want them to be printed on OLED display
Why do they have to be ints when you could at least make them bytes ? That would waste less memory but could still be improved on if needs be
I tried modified version of your code:
void printByteDisplay(byte aByte, byte nbBits = 8, int a=0, int b=0) {
if (nbBits == 0) return;
for (int i = 0 ; i <= nbBits - 1; i++) {
//display.write(bitRead(aByte, i) == 0 ? '0' : '1'); //
display.setCursor(a, b+i*9);
display.println(bitRead(aByte, i) == 0 ? '0' : '1');
//Serial.println(bitRead(aByte, i) == 0 ? '0' : '1');
}
//Serial.println("");
}
Achtung: I am trying to print it on OLED display. The problem is that it shows
1
0
0
0
instead of
0
0
0
1
Thank you, I will change the type.
I changed
display.println(bitRead(aByte, i) == 0 ? '0' : '1');
to
display.println(bitRead(aByte, nbBits - 1-i) == 0 ? '0' : '1');
Now it works perfect. Thank you for your answer.
great ![]()
(you don't want println() but just print and could use write() instead of print() when you send only 1 char, it's more efficient)
This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.