C + + binary Flip Case Analysis _c language

Source: Internet
Author: User
Tags int size

This article describes the C + + binary Flip method, the commonly used several solutions listed for everyone to compare the choice. Specifically as follows:

Let's take a look at a relatively clumsy algorithm:

#include <iostream>

using namespace std;

void printbinary (unsigned char str, int size = 1)
{
 int flag = 0x01;
 for (int i = 0; i < size; i++)
 {for
 (int i = 0; i < 8; i++)
 {
  if (str & (0x01 << (7-i)) )
  cout << "1";
  else
  cout << "0";
 }
 cout << Endl;;
 }}

unsigned char myswap (unsigned char data)
{
 unsigned char flag = 0x01;
 for (int i = 0, j = 7; I < J; i++, j--)
 {
 Int. right = data & (0x01 << i);
 int left = data & (0x01 << j);
 Data &= ~ (0x01 << j);
 Data &= ~ (0x01 << i);
 int dist = j-i;
 Data |= (right << Dist);
 Data |= (left >> dist);
 }
 return data;
}

void main (void)
{
 char source=0x07;
 int i;
 Printbinary (source, 1);
 unsigned char result = Myswap (source);
 Printbinary (result);
}

The following flip program is simple and efficient relative to the above example:

unsigned char swapbinary (unsigned char data)
{
 int sign = 1;
 unsigned char result = 0;
 for (int i = 0; I <= 7; i++)
 {result
 = (data & (sign << i)) >> i) << (7-i);
 } return result

 ;
}

The following reverse procedure is easier to understand:

unsigned char swapBinary2 (unsigned char data)
{
 data= (data & 0xf0) >> 4) | (Data & 0x0f) << 4); 
 Data= ((Data & 0xCC) >> 2) | (Data & 0x33) << 2); 
 Data= ((Data & 0xAA) >> 1) | (Data & 0x55) << 1); 
 return data; 
}

In the end, this Super Cow reversal program is a bunker ...

unsigned char codetable[16]={0x00, 0x08, 0x04, 0x0c, 0x02, 0x0a, 0x06, 0x0e, 0x01, 0x09, 0x05, 0x0d, 0x03, 0x0b, 0x07, 0x0 f}; 

unsigned char swapBinary3 (unsigned char data) 
{return 
 (Codetable[data >> 4]) | (Codetable[data & 0x0f] << 4);
}

I hope this article is helpful to the learning of C + + program algorithm design.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.