# How to shift out binary digits to a PIN

Hi I guess to start I know there is the shiftout function, but I am trying to get a better grasp of how it works. The code below shows how I was trying to turn an LED on and off in different patterns by using B00011101, etc. I guess my first side question is the B means binary correct? Are there other prefixes for HEX, OCT, etc? Also If I want to make it 16bits long I would just change the type to something other than byte?

In the code below I thought I could just make an array and just kind of reference the parts of it, but it doesn’t work. In the second code I tried to use if statements to make sure HIGHs and LOWs were used instead of ones and zeros.

But, it looks like the problem is referencing the individual bits.

Thanks for the help

``````void setup() {
pinMode(12,OUTPUT);
}

void loop() {
byte a[]={B10101010};

for (int i=1;i<9;i++){
digitalWrite(12,a[i]);
delay(1000);
}
}
``````

or

``````void setup() {
pinMode(12,OUTPUT);
}

void loop() {
byte a[]={B10101010};

for (int i=1;i<9;i++){

if (a[i]==1){
digitalWrite(12,HIGH);
}

else{
digitalWrite(12,LOW);
}
delay(1000);

}
}
``````

byte does not need to be an array

byte foo = B00000000;

oh and 0x is hex (0xFF) ,0 is octal (023),the others I dont know *yet

The shiftOut function is for sending data to SPI devices. LED's are not SPI devices. The rest of your code has nothing to do with the shiftOut function.

Instead, you are trying to access the individual bits in a byte, and going about it all wrong.

There are functions that simplify bit access. Use Help + Reference on the IDE to see the help files. Click on the (extended) link, and look at bitRead and bitWrite for help on getting and setting individual bits in a byte.

But, it looks like the problem is referencing the individual bits.

Yup. Your problem is that C and C++ don’t treat a byte as “an array of bits”: it’s a “number”, a smaller version of an unsigned int.

``````void setup() {
pinMode(12,OUTPUT);
}

void loop() {
byte a = 0xcc;
// Shift out a, MSB first
for (int i = 0; i < 8; i++){
if (a & 0x80)
digitalWrite(12, HIGH);
else
digitalWrite(12, LOW);
a = a << 1;
delay(1000);
}
}
``````

There are a couple of points of style worth noting, in addition to the substance.

1. I used “0xcc” because “B10101010” is a non-standard language extension, and portable code is generally considered A Good ThingTM (although the binary constant is more self-documenting in this case)

2. Whitespace is your friend. In an age of terabyte hard drives, it’s basically “free”, and you’ll almost always be happier that you used it when you’re trying to decipher your code 6 months after you wrote it

3. Because C starts array indexes at 0, it’s a good habit to start loops from 0. Even if you’re not going to be indexing an array, it’s so strong a custom among C programmers that starting from 1 might even mislead someone trying to read your code.

Ran