Convert binary to palindrome function

Quote:

> Having trouble creating a function that converts a 8-bit binary number into

> a 16-bit palindrome using the C bitwise operators, such as Bitwise AND,

> Bitwise OR,... Left shift <<. I tried several attempts at using left shift,

> << SIZE - 1....

Imagine you have two stacks. S1 is initially empty and S2

contains some data. Now if you repeatedly POP the topmost item

from S2 and PUSH it to S1, until S2 becomes empty, in the end you

have moved all the data from S2 to S1 and reversed its order in

the process. (The original top is now in the bottom, because it

was popped first and pushed first.)

You can use this algorithm. Each item is a bit, and each stack

is an unsigned (don't forget that!) integer. Operations are:

PUSH: stack = (stack << 1) | item;

POP: item = (stack & 1); stack >>= 1;

Because the integers don't remember how many bits are in the

stack, you need a separate counter.

After you have reversed the order of bits, you can form the

palindrome by combining the reversed value and the original value

with << and | operators.

There are numerous other ways to reverse a bit string. One of

them moves several bits at a time, like this:

abcdefgh

badcfehg

dcbahgfe

hgfedcba

Quote:

> /*------------------------------------------------------------------------

> * This function converts a binary number into a palindrome using strrev()

> * Paramaters: *binstr, *palin

> * Return Value: palinstr

> *------------------------------------------------------------------------

> */

I like stating the preconditions of the function in the comment:

This function generates a palindrome from the string BINSTR and

stores the result in the buffer PALINSTR. BINSTR can be at

most SIZE characters long, and PALINSTR must have room for

2*strlen(BINSTR)+1 characters. The palindrome contains BINSTR

first reversed and then in original order. The function

returns PALINSTR.

Quote:

> char * bintopalindrome(char * binstr, char * palinstr)

As the function is not intended to change *binstr, you should

make that parameter point to const.

Quote:

> {

> char temp[SIZE +1];

> *temp = '\0';

> *palinstr = '\0';

> strcpy(temp, binstr);

> strcat(palinstr,strrev(temp));

> strcat(palinstr,binstr);

> return palinstr;

> }

Clearing *temp is not necessary because you overwrite the string

with a new one anyway. Clearing *palinstr is necessary if you

strcat to it, but if you change the first strcat to strcmp, you

needn't clear that either.

Also note that you can get rid of temp (and thus the SIZE

limitation) altogether if you take advantage of strrev()

reversing the string in place: copy binstr to palinstr, reverse

it there and append the rest.

(Extra exercise: write a portable implementation for the

non-standard strrev function, and call it something that doesn't

begin with "str".)

--