I have written a Manchester Encoding encoder / decoder based on my misconception of how it works (whoops). My encoder accepts an array of ones and zeroes, and returns the 'manchester encoded' data (pretending there is a constant clock to overlay onto the data). I am reasonably new to C++, and would like to advance my knowledge and coding skill in it, hence why I coded this small application. I am looking for ways to improve my code, as well as ways to increase its efficiency.
Main.cpp
#include <iostream>
#include "Manchester.h"
int main()
{
int data[] = { 1, 1, 0, 0 }; // Some unencoded data
int* encoded = Manchester::encode(data, 4);
int* decoded = Manchester::decode(encoded, 8);
return 0;
}
Manchester.cpp
#include "Manchester.h"
#include <stdexcept>
#include <sstream>
#include <cstring>
#include <cstdlib>
#ifdef DEBUG
#include <iostream>
#endif
int *Manchester::encode(int *data, int length)
{
int *output = new int[length * 2];
for (int i = 0; i < length; i++)
{
// Work out the array indexes to use
int bid = i * 2;
int nbid = bid + 1;
// Get the data
int real = data[i];
int bit = 0;
int nbit = 0;
// Work out what it is
switch (real)
{
case 0:
bit = MANCHESTER_ZERO[0] - '0'; // Subtract 48 to work out the real value
nbit = MANCHESTER_ZERO[1] - '0';
break;
case 1:
bit = MANCHESTER_ONE[0] - '0'; // Subtract 48 to work out the real value
nbit = MANCHESTER_ONE[1] - '0';
break;
}
#ifdef DEBUG
std::cout << "[encode] " << real << " [" << bit << nbit << "]" << std::endl;
#endif
output[bid] = bit;
output[nbid] = nbit;
}
return output;
}
int *Manchester::decode(int *data, int length)
{
if ((length % 2) != 0)
{
throw std::range_error("length is not a multiple of 2");
}
int *output = new int[length / 2];
for (int i = 0; i < (length / 2); i++)
{
// Work out the array indexes to use
int bid = i * 2;
int nbid = bid + 1;
// Get the data
int bit = data[bid];
int nbit = data[nbid];
// Put the data into a stringstream for comparison
std::stringstream con;
con << bit << nbit;
const char* sbit = con.str().c_str();
int real = 0;
// Compare the data and work out the value
if (strcmp(sbit, MANCHESTER_ONE) == 0)
{
real = 1;
} else if (strcmp(sbit, MANCHESTER_ZERO) == 0) {
real = 0;
}
#ifdef DEBUG
std::cout << "[decode] bit: " << bit << nbit << " [" << real << "]" << std::endl;
#endif
output[i] = real;
}
return output;
}
Manchester.h
#ifndef MANCHESTER_H
#define MANCHESTER_H
#define DEBUG
#define MANCHESTER_ONE "01"
#define MANCHESTER_ZERO "10"
class Manchester
{
public:
static int *encode(int *data, int length);
static int *decode(int *data, int length);
};
#endif
decode
twice inencode
since you will divide it to half w/c is equal to length of array. \$\endgroup\$ – mr5 Oct 28 '13 at 18:21