binary to an array

Status
Not open for further replies.

keny

New Member
binary to an array in C

ok I've got my spi working, but I am wondering how I can turn a binary number into an array of same numbers i.o.w.

how to make this: 0b10110100
into this

binarray[0] = 1
binarray[1] = 0
binarray[2] = 1
binarray[3] = 1
binarray[4] = 0
binarray[5] = 1
binarray[6] = 0
binarray[7] = 0

...so i can assign the individual numbers to their appropriate output pins that aren't all on the same port.
 
Last edited:
Code:
    for(i=0;i<8;i++){
        binarray[i]=(data>>i)&1;
    }
or, for the other way around,
Code:
    for(i=0;i<8;i++){
        binarray[i]=(data>>(7-i))&1;
    }

Mike.
 
ok but now im kind of weirded out. I don't know if my issue is coming from bad coding or mplab/HI-Tech C.

here's what's going on:
Code:
	unsigned char rxdata;
        unsigned char txdata;
        txdata = 0b11110011;     // set an arbitrary binizzel
        rxdata = SSPBUF;        // bring the binary from SDI
        SSPBUF = txdata;        // assign outgoing binary to buffer
        //while (!BF);              // cut for MPLAB Sim

        unsigned char binarray[];  

               for( i = 0; i < 8; i++){

                // using txdata for debugging, should be rxdata
                   binarray[i] = ( txdata >> i) & 1;   // this line right here

            }

Ok the strangeness is happening like this...

in the watch window, as I get into the for loop everything looks cool.
i == 0.
I hit the line of code with the >> in it and txdata becomes 0x01.
Subsequent loops: txdata stays 0x01, should stay 0xF3...

the watch window does not display binarray, it just says "" which I dont get either...

Has it really been that long of a day?
 
Last edited:
That code fails to compile for me. I had to change it to,
Code:
unsigned char rxdata,i;
unsigned char txdata;
unsigned char binarray[[COLOR="red"]8[/COLOR]];  
    txdata = 0b11110011;     // set an arbitrary binizzel
    rxdata = SSPBUF;        // bring the binary from SDI
    SSPBUF = txdata;        // assign outgoing binary to buffer

    for( i = 0; i < 8; i++){
        // using txdata for debugging, should be rxdata
        binarray[i] = ( txdata >> i) & 1;   // this line right here
    }

With the change it works as expected.

Mike.
Watch window attached.
 

Attachments

  • watch.png
    18.2 KB · Views: 133
Last edited:
aaaah the ol' "didn't initialize the array right". One of these days i'll be good at this stuff and see it like a hawk. For the meantime thanks!!!!
 
Status
Not open for further replies.
Cookies are required to use this site. You must accept them to continue using the site. Learn more…