1

Code :

PORTB = "0b11010000";

Question :

I am now learning to program a 8 bit microcontroller PIC18F8722 using C language on MPLab.

How can I mirror this binary PORTB bits from "11010000" to "00001011"?

Paul R
  • 208,748
  • 37
  • 389
  • 560
Casper
  • 4,435
  • 10
  • 41
  • 72
  • 2
    This is a straightforward bit reversal operation - you can either use a LUT (256 entries) or one of the various well-known bit-level hacks. See e.g. [Best Algorithm for Bit Reversal ( from MSB->LSB to LSB->MSB) in C](http://stackoverflow.com/questions/746171/best-algorithm-for-bit-reversal-from-msb-lsb-to-lsb-msb-in-c) – Paul R Aug 19 '14 at 14:29
  • 1
    ALso, that "code" is very dubious. `PORTB` is probably not a string, and there's no such thing as `0b`-prefixes in C. – unwind Aug 19 '14 at 15:13

2 Answers2

3

The best Article about Bits Operations in C is Bit Twiddling Hacks written by Sean Eron Anderson. He has provided many types Bit functions to do things in optimized way. His methods are accepted worldwide and many library use them to do things in Optimized way. The Way of reverse of Bits provided by him:

  • Reversing bit sequences:
    • Reverse bits the obvious way
    • Reverse bits in word by lookup table
    • Reverse the bits in a byte with 3 operations (64-bit multiply and modulus division)
    • Reverse the bits in a byte with 4 operations (64-bit multiply, no division)
    • Reverse the bits in a byte with 7 operations (no 64-bit, only 32)
    • Reverse an N-bit quantity in parallel with 5 * lg(N) operations

Obvious way

unsigned int v;              // input bits to be reversed
unsigned int r = v;         // r will be reversed bits of v; first get LSB of v
int s = sizeof(v) * CHAR_BIT - 1; // extra shift needed at end

for (v >>= 1; v; v >>= 1){   
    r <<= 1;
    r |= v & 1;
    s--;
 }
r <<= s; // shift when v's highest bits are zero

For other types view the article

Vineet1982
  • 7,730
  • 4
  • 32
  • 67
3

This is rendition of an embedded guy:

unsigned char Reverse_bits(unsigned char num){

    int i=7; //size of unsigned char -1, on most machine is 8bits
    unsigned char j=0;
    unsigned char temp=0;

    while(i>=0){
    temp |= ((num>>j)&1)<< i;
    i--;
    j++;
    }
    return(temp); 

}

To use it just pass it Port_B where it should be defined in your device header file as something like:

# define Port_B *(unsigned char*)( hard_coded_address_of_portB)
Paul R
  • 208,748
  • 37
  • 389
  • 560
  • If the number is shifted left, all the bits except the last one will be lost. So what's the point of right shifting again? – Sadat Rafi May 05 '20 at 17:36