[ yt1nvs @ 12.03.2015. 15:27 ] @
posto sam ja jos svez u C-u interesuje me sledece : unsigned int a; kako sad izdvojiti vrednost nekog bita 0-15 iz ove promenljive i prikazati npr. na GP0 (12f serija pic) GP0 = ??? |
[ yt1nvs @ 12.03.2015. 15:27 ] @
[ npejcic @ 12.03.2015. 19:16 ] @
Brzinski odgovor i jedan od načina je ovaj:
if(a & ((unsigned int)1 << 12)) // Ovde podešavaš koji bit proveravas, recimo u nasem primeru to je 12. bit { // Ako je bit 12 log. "1" GP0 = 1; } else { // Ako je bit 12 log. "0" GP0 = 0; } Korišćenjem maske bitova, ukoliko je 12 bit u promenljivoj a 1, izraz (a & ((unsigned int)1 << 12)) će biti vrednost različita od 0, pa će i GP0 biti na logičkoj "1", i obratno. [ tavance @ 12.03.2015. 20:10 ] @
Može i ovako, ali je brže uraditi logičko I (ako treba više od dva šiftovanja - odokativno) sa vrednošću kod koje je željeni bit postavljen na 1. Zatim se testira taj bit i to je to, najbrže se izvršava.
[ goran_68 @ 12.03.2015. 21:08 ] @
Evo ti primer.
a je tvoja int promenljiva a pos je promenljiva koja definiše poziciju bita koji testiraš. U primeru, GP0 uzima redom vrednosti bitova iz promenljive a koja je postavljena na 0xF156 Code: #include <pic.h> void main(void) { unsigned int a = 0xF156; unsigned char pos; CMCON = 0x07; ANSEL = 0; TRISIO = 0; for(pos=0;pos<16;pos++) { GP0 = ((a & (1 << pos)) ? 1:0); } } [ bogdan.kecman @ 12.03.2015. 21:21 ] @
drugi google hit
Citat: Setting a bit Use the bitwise OR operator (|) to set a bit. number |= 1 << x; That will set bit x. Clearing a bit Use the bitwise AND operator (&) to clear a bit. number &= ~(1 << x); That will clear bit x. You must invert the bit string with the bitwise NOT operator (~), then AND it. Toggling a bit The XOR operator (^) can be used to toggle a bit. number ^= 1 << x; That will toggle bit x. Checking a bit You didn't ask for this but I might as well add it. To check a bit, shift the number x to the right, then bitwise AND it: bit = (number >> x) & 1; That will put the value of bit x into the variable bit. Changing the nth bit to x Setting the nth bit to either 1 or 0 can be achieved with the following: number ^= (-x ^ number) & (1 << n); Bit n will be set if x is 1, and cleared if x is 0. ista strana, malo nize Citat: #define BIT_SET(a,b) ((a) |= (1<<(b))) #define BIT_CLEAR(a,b) ((a) &= ~(1<<(b))) #define BIT_FLIP(a,b) ((a) ^= (1<<(b))) #define BIT_CHECK(a,b) ((a) & (1<<(b))) /* x=target variable, y=mask */ #define BITMASK_SET(x,y) ((x) |= (y)) #define BITMASK_CLEAR(x,y) ((x) &= (~(y))) #define BITMASK_FLIP(x,y) ((x) ^= (y)) #define BITMASK_CHECK(x,y) ((x) & (y)) [ yt1nvs @ 12.03.2015. 23:19 ] @
Hvala svima na odgovoru,sad mi je jasno.
[ bogdan.kecman @ 12.03.2015. 23:42 ] @
![]() [ ZAS011 @ 13.03.2015. 07:50 ] @
![]() Copyright (C) 2001-2025 by www.elitesecurity.org. All rights reserved.
|