[ create a new paste ] login | about

Link: http://codepad.org/29hae1jr    [ raw code | output | fork ]

ninwa - C++, pasted on Oct 7:
/* COSC 221 : Proj. 1, Emulated Circuits

   Author: Joseph Bleau
   Date: October 3rd, 2012
   Details: Using vector<bool> as our transport type we emulate the
            functionality of variably sized decoders, encoders, and muxers.
            The size of the output is automatically and appropriately 
            determined by the width of the input.
*/

#include <bitset>
#include <vector>
#include <iostream>
#include <math.h>

unsigned most_sig_dig(const std::vector<bool>& in)
{
	for(int i = in.size()-1; i >= 0; i--)
		if(in.at(i))
			return (unsigned) i;

	return 0;
}

template<class T>
void reverse_print_vector(const std::vector<T>& vec)
{
  for(int i = vec.size()-1; i >= 0; i--)
  {
	  std::cout << (int) vec[i];
  }
}

std::vector<bool> encoder(const std::vector<bool>& in)
{
	double out_sz = log2(in.size());
	if(out_sz - (long) out_sz > 0)
		out_sz++;

	std::vector<bool> out((size_t)out_sz, 0);

	unsigned sigdig = most_sig_dig(in);
	for(int i = out.size()-1; i >= 0; i--)
	{
		int bit = (sigdig >> i) & 1;
		out.at(i) = (bool) bit;
	}

	return out;
}

std::vector<bool> decoder(const std::vector<bool>& in)
{
	double out_sz = pow((double) 2, (double)in.size());
	std::vector<bool> out((size_t)out_sz, 0);

	int idx = 1;
	for(int i = 0; i < (int) in.size(); i++)
		idx += (in[i]) ? (int) pow(2.0L, i) : 0;

	out[idx-1] = true;
	return out;
}


bool mux(const std::vector<bool>& in, const std::vector<bool>& sw)
{
	int sigdig = most_sig_dig(decoder(sw));
	if(sigdig == 0)
		return false;

	return in[sigdig-1];
}

int main()
{
  // 8 to 3 encoder test (using vec<bool>)
  std::vector<bool> vb_in(8,0);
  vb_in[4] = true; // 10000
  std::vector<bool> vb_out = encoder(vb_in);
  reverse_print_vector(vb_in);
  std::cout << " --> [encoder] --> ";
  reverse_print_vector(vb_out);
  std::cout << "\n\n";

  // 3 to 8 decoder test (using vec<bool>)
  std::vector<bool> vb_out2 = decoder(vb_out); // using output from encoder from last test
  reverse_print_vector(vb_out);
  std::cout << " --> [decoder] --> ";
  reverse_print_vector(vb_out2);
  std::cout << "\n\n";

  // 8 to 1 muxer test, using input from 8 to 3 encoder test
  std::vector<bool> sw(3,0); // switch input for muxer, set to 100
  sw[2] = true;

  bool muxer_out = mux(vb_in, sw);
  reverse_print_vector(vb_in);
  std::cout << " --- > +-----+ " << "\n";
  std::cout << "               | mux | --> " << (int) muxer_out << "\n";
  reverse_print_vector(sw);
  std::cout << "      --- > +-----+\n";
}


Output:
1
2
3
4
5
6
7
00010000 --> [encoder] --> 100

100 --> [decoder] --> 00010000

00010000 --- > +-----+ 
               | mux | --> 0
100      --- > +-----+


Create a new paste based on this one


Comments: