Continue to Site

Welcome to EDAboard.com

Welcome to our site! EDAboard.com is an international Electronics Discussion Forum focused on EDA software, circuits, schematics, books, theory, papers, asic, pld, 8051, DSP, Network, RF, Analog Design, PCB, Service Manuals... and a whole lot more! To participate you need to register. Registration is free. Click here to register now.

How to write a C program which exchange the bits in a byte?

Status
Not open for further replies.

kukurigu

Junior Member level 3
Joined
Dec 14, 2002
Messages
25
Helped
1
Reputation
2
Reaction score
1
Trophy points
1,283
Activity points
272
c program to exchange the nibbles

How to write a C program which exchange the bits in a byte (i.e. mirror the bits)?
There are different approaches but I am looking for the fast one!
 

Re: How to write a C program which exchange the bits in a by

use a look up table
 

I haven't tested this but the geneal idea is right. Should work.


int MirrorInt(value)
{

int lastbit = 15;
int i;

for ( i = 0; i <= lastbit; i++)
(
if ( 1 << i && value)
value = value || 1 << (lastbit - i );
else
value = value && !(1 <<(lastbit - i ));


)

return value;

}
 

Kukurigu what you are trying to ask. Do you want to exchange nibbles in a byte or tou want to reverse the number in a byte i.e LSB will be MSB and vice versa

Moreover jhbbunch your program seems to be wrong plz check it out
 

Re: How to write a C program which exchange the bits in a by

I want to reverse the bits (i.e mirror) bit7 <-> bit0, bit6 <-> bit1 and so on.
 

Re: How to write a C program which exchange the bits in a by

Not my idea!

Code:
char reverse (char n) {
  n = n & 0b11110000 >> 4 | n & 0b00001111 << 4;  // efghabcd
  n = n & 0b11001100 >> 2 | n & 0b00110011 << 2;  // ghefcdab 
  n = n & 0b10101010 >> 1 | n & 0b01010101 << 1;  // hgfedcba
  return n;
}
 

Re: How to write a C program which exchange the bits in a by

assign the whole port bits 0-7 as a word
the use modulus

portword= ~portword

this will invert the word then you can shift out what bit you want

bit=(BOOL) (portword<<x) // where x is the bit you want
 

Re: How to write a C program which exchange the bits in a by

If what you want is just fast may be look-up-table is a better method. But I think for 8-bits byte we can code in a "stupid" way like this:

void reverse_byte(byte &a)
{
byte b ;

b = *a;
*a=0;
*a += (b&(1<<7))>>7;
*a += (b&(1<<6))>>5;
*a += (b&(1<<5))>>3;
*a += (b&(1<<4))>>1;
*a += (b&(1<<3))<<1;
*a += (b&(1<<2))<<3;
*a += (b&(1<<1))<<5;
*a += (b&(1<<0))<<7;

return;
}

I hope this can work and the compiler can optimize it to simple asm instructions.
 

void reverse_byte(byte &a)
isn't this some C++ with reference arg?
I don't think it will work with a non-AnsI C compiler for 8 bit mcu.
 

Re: How to write a C program which exchange the bits in a by

Sorry.
It should be (byte *a)
 

Status
Not open for further replies.

Part and Inventory Search

Welcome to EDABoard.com

Sponsor

Back
Top