Esempio n. 1
0
/*
 * bool testWithLength(int length)
 *
 * Creates three random vectors with the given length and times the performance of scalar_fma() and
 * vectorized_fma() with these vectors as input.
 *
 * Returns true if the results match.
 */
bool testWithLength(int length) {
  printf("Test length: %d\n", length);

  // Create (and clone) three vectors with the given length
  struct doubleVector a = random_vector(length);
  struct doubleVector b = random_vector(length);
  struct doubleVector c = random_vector(length);

  struct doubleVector a2 = vector_clone(&a);
  struct doubleVector b2 = vector_clone(&b);
  struct doubleVector c2 = vector_clone(&c);
  
 
  // Test scalar performance 
  printf("\tScalar cycle count: %d\n", perfTest(&a, &b, &c, scalar_fma));
 
  // Test vector performance
  printf("\tVector cycle count: %d\n", perfTest(&a2, &b2, &c2, vector_fma));

  // Compare results
  bool correct = vector_compare(&a, &a2);
  printf("\t%s\n", correct ? "MATCH" : "NO MATCH");
  
  // Free dynamic resources
  free(a.data);
  free(b.data);
  free(c.data);
  free(a2.data);
  free(b2.data);
  free(c2.data);

  return correct;
}
Esempio n. 2
0
inline void
invoke_reuse_helper(Encoder encoder, Decoder decoder)
{
    std::vector<uint8_t> payload(encoder->payload_size());

    std::vector<uint8_t> data_in = random_vector(encoder->block_size());
    sak::mutable_storage storage_in = sak::storage(data_in);

    encoder->set_symbols(storage_in);

    // Set the encoder non-systematic
    if(kodo::is_systematic_encoder(encoder))
        kodo::set_systematic_off(encoder);

    while( !decoder->is_complete() )
    {
        uint32_t payload_used = encoder->encode( &payload[0] );
        EXPECT_TRUE(payload_used <= encoder->payload_size());

        decoder->decode( &payload[0] );
    }

    std::vector<uint8_t> data_out(decoder->block_size(), '\0');
    decoder->copy_symbols(sak::storage(data_out));

    EXPECT_TRUE(std::equal(data_out.begin(),
                           data_out.end(),
                           data_in.begin()));

}
Esempio n. 3
0
int main(void)
{
	init_prg();

	uint l = random_dim();
	uint n = random_dim();
	float *ys = random_vector(n);
	float eta = 0.001;

	float *Ys = random_matrix(n, l);

	perturbate(l, n, ys, eta, Ys);

	for (uint j = 1; j <= l; j++) {
		for (uint i = 1; i <= n; i++) {
			assert(abs((M_IDX(Ys, n, i, j) - V_IDX(ys, i))
				   / V_IDX(ys, i)) <= eta);
		}
	}

	free(Ys);
	free(ys);

	return 0;
}
int main()
{
	for (size_t n = 0; n <= 100; ++n)
	{
		std::vector< int > v = random_vector(n);

		/*
		 * since v has only values in [-100,100], the sum of any
		 * pair of elements in v must be in [-200,200]
		 */
		for (int t = -250; t <= 250; ++t)
		{
			std::vector< int_pair > pairs_1 = two_sum_1(v,t);
			std::vector< int_pair > pairs_2 = two_sum_2(v,t);

			std::sort(pairs_1.begin(), pairs_1.end());

			assert(pairs_1 == pairs_2);

			for (auto p : pairs_1)
			{
				assert(p.first + p.second == t);
			}
		}

		std::cout << "passed random test for array of size " << n << std::endl;
	}

	return 0;
}
Esempio n. 5
0
void random_matrix(gsl_matrix *input, double parameter,double (* func)(const gsl_rng *, double )){

  gsl_vector *temp = gsl_vector_alloc(input->size1 * input->size2);
  random_vector(temp, parameter, func);
  gsl_matrix_view temp_view = gsl_matrix_view_array(temp->data, input->size1, input->size2);
  gsl_matrix_memcpy(input, &temp_view.matrix);
  gsl_vector_free(temp);
}
Esempio n. 6
0
void BoundingLayer::initialize_random(void)
{
   Vector<double> random_vector(4);
   random_vector.randomize_normal();

   std::sort(random_vector.begin(), random_vector.end());

   lower_bounds.randomize_uniform(random_vector[0], random_vector[1]);
   upper_bounds.randomize_uniform(random_vector[2], random_vector[3]);
}
    inline std::vector<std::size_t> newPermutation(const std::size_t size)
    {
        std::vector<std::size_t> random_vector(size);
        for (std::size_t i = 0; i < size; ++i) {
            random_vector[i] = i;
        }

        std::shuffle(random_vector.begin(), random_vector.end(), gen_);
        return random_vector;
    }
void inject_command(pcap_t *fp, gcry_cipher_hd_t * hd,char * dst_mac, char * command, int len, unsigned long * seqnum){
        char pkt[1000];
        u_char buf[1024];
        u_char iv[GCRY_IVLEN]={0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11};
        len+=SEQ_LEN;
        char pkt_len[6];


        char type[] =  {    0x00,0x00,0x0d,0x00,0x04,0x80,0x02,0x00,0x02,0x00,0x00,0x00,0x00,0x80,0x00,0x00,0x00,0xff,0xff,0xff,0xff,0xff,0xff,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,
			    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x64,0x00,0x11,0x00,0x00,0x05,
		             'I', 'N', 'T', 'C', 'P',0x01,0x04,0x82,0x84,0x8b,0x96,0x03,0x01,0x0c,0x04,0x06,0x01,0x02,0x00,0x00,0x00,0x00,0x05,0x04,0x00,0x01,0x00,0x00,0xdd,0x18,0x00,0x50,0xf2,0x01,0x01,
			    0x00,0x00,0x50,0xf2,0x04,0x01,0x00,0x00,0x50,0xf2,0x04,0x01,0x00,0x00,0x50,0xf2,0x02,0x00,0x00}; 



        u_int tlen=len+MAC_LEN+CHECKSUM_LEN+GCRY_IVLEN;
        random_vector(iv,GCRY_IVLEN);
        memcpy(&pkt[0],dst_mac,MAC_LEN);
        memcpy(&pkt[MAC_LEN],iv,GCRY_IVLEN);
        gcry_cipher_setiv(*hd,iv, GCRY_IVLEN);


        char cmdseq[1000];
        memcpy(cmdseq,command,len);
        u_int ac=0;
        (*seqnum)++;
        if(*seqnum>0xFFFFFFFF){*seqnum=0x01;}
        for(ac=0;ac<SEQ_LEN;ac++){
                cmdseq[len-1-ac]=(char)((*seqnum)>>(ac*8));
        }

        gcry_cipher_encrypt(*hd, &pkt[GCRY_IVLEN+MAC_LEN],len , cmdseq, len);

        u_int chk=checksum(pkt,tlen);
        u_char chkarr[CHECKSUM_LEN];
        chkarr[0]=(chk>>8);
        chkarr[1]=chk&0x00FF;

        memcpy(&pkt[GCRY_IVLEN+MAC_LEN+len], chkarr,CHECKSUM_LEN);
        memcpy(buf, type, sizeof(type));
        memcpy(buf+sizeof(type), pkt, tlen);

	#ifndef MANDO_ABORDO
        print_vector(pkt,tlen);
        #endif

        for(ac=0;ac<BEACONS_PER_REQUEST;ac++){
	    int inj=pcap_inject(fp,buf, sizeof(type)+sizeof(pkt_len)+tlen);
	    #ifndef MANDO_ABORDO
		printf("\r\n INJ %i",inj);
	    #endif	
            
        }
        
}
Esempio n. 9
0
void Scene::generate_points_in(const unsigned int nb_points,
                               const double min,
                               const double max)
{
    if(m_pPolyhedron == NULL)
    {
        std::cout << "Load polyhedron first." << std::endl;
        return;
    }

    typedef CGAL::AABB_face_graph_triangle_primitive<Polyhedron> Primitive;
    typedef CGAL::AABB_traits<Kernel, Primitive> Traits;
    typedef CGAL::AABB_tree<Traits> Tree;

    std::cout << "Construct AABB tree...";
    Tree tree(faces(*m_pPolyhedron).first, faces(*m_pPolyhedron).second, *m_pPolyhedron);
    std::cout << "done." << std::endl;

    CGAL::Timer timer;
    timer.start();
    std::cout << "Generate " << nb_points << " points in interval ["
              << min << ";" << max << "]";

    unsigned int nb_trials = 0;
    Vector vec = random_vector();
    while(m_points.size() < nb_points)
    {
        Point p = random_point(tree.bbox());

        // measure distance
        FT signed_distance = std::sqrt(tree.squared_distance(p));

        // measure sign
        Ray ray(p,vec);
        int nb_intersections = (int)tree.number_of_intersected_primitives(ray);
        if(nb_intersections % 2 != 0)
            signed_distance *= -1.0;

        if(signed_distance >= min &&
                signed_distance <= max)
        {
            m_points.push_back(p);
            if(m_points.size()%(nb_points/10) == 0)
                std::cout << "."; // ASCII progress bar
        }
        nb_trials++;
    }
    double speed = (double)nb_trials / timer.time();
    std::cout << "done (" << nb_trials << " trials, "
              << timer.time() << " s, "
              << speed << " queries/s)" << std::endl;
    changed();
}
Esempio n. 10
0
			/// Return a random multivariate gaussian point
			VectorType random_gaussian(int arg_dim){

				VectorType random_vector;
				random_vector.setZero(arg_dim);

				for(int ii=0; ii < random_vector.size(); ii++){

					random_vector(ii) = random_gaussian();
				}

				return random_vector;
			}
TEST(TestReedSolomonCodes, test_encode_decode)
{
    {
        kodo::rs_encoder<fifi::binary8>::factory encoder_factory(255, 1600);
        kodo::rs_decoder<fifi::binary8>::factory decoder_factory(255, 1600);

        uint32_t symbols = rand_symbols(255);
        uint32_t symbol_size = rand_symbol_size();

        encoder_factory.set_symbols(symbols);
        encoder_factory.set_symbol_size(symbol_size);

        decoder_factory.set_symbols(symbols);
        decoder_factory.set_symbol_size(symbol_size);

        auto encoder = encoder_factory.build();
        auto decoder = decoder_factory.build();

        // Encode/decode operations
        EXPECT_TRUE(encoder->payload_size() == decoder->payload_size());

        std::vector<uint8_t> payload(encoder->payload_size());
        std::vector<uint8_t> data_in = random_vector(encoder->block_size());

        encoder->set_symbols(sak::storage(data_in));

        uint32_t symbol_count = 0;
        while( !decoder->is_complete() )
        {
            encoder->encode( &payload[0] );
            decoder->decode( &payload[0] );
            ++symbol_count;
        }

        // A reed solomon code should be able to decode
        // with exactly k symbols
        EXPECT_EQ(symbol_count, symbols);

        std::vector<uint8_t> data_out(decoder->block_size(), '\0');
        decoder->copy_symbols(sak::storage(data_out));

        EXPECT_TRUE(std::equal(data_out.begin(),
                               data_out.end(),
                               data_in.begin()));

    }

}
Esempio n. 12
0
int main()
{
	srand(time(0));
	std::cout << add(1.12, 2.0) << std::endl;
	std::cout << add_auto(1.12, 2.0) << std::endl;
	std::cout << "POW! 2^10 " << pow(2, 10) << std::endl;
	std::cout << "8^0 " << pow(8, 0) << std::endl;

	std::vector<double> test_v = random_vector(12);
	print_vector(test_v);
	sort_vector(test_v);
	std::cout << "Sorted: " << std::endl;
	print_vector(test_v);

    return 0;
}
Esempio n. 13
0
bool
test_cholesky_1down (void)
{
	int			info;
	c_matrix	*a;
	c_matrix	*c;
	c_matrix	*l;
	c_vector	*u;
	double		nrm;

	/* posdef symmetry matrix *a */
	{
		int			i;
		c_matrix	*a0 = random_matrix (size1, size1);
		a = c_matrix_transpose_dot_matrix (1., a0, a0);
		c_matrix_free (a0);
		for (i = 0; i < size1; i++) c_matrix_set (a, i, i, c_matrix_get(a, i, i) + 1.);
	}

	l = c_matrix_alloc (a->size1, a->size2);
	c_matrix_memcpy (l, a);
	u = random_vector (size1);
	c_vector_scale (u, 0.1);
	{
		c_matrix	*ut = c_matrix_view_array (u->size, 1, u->size, u->data);
		c = c_matrix_dot_matrix_transpose (1., ut, ut);
		c_matrix_free (ut);
		c_matrix_sub (a, c);
		c_matrix_free (c);
		c_linalg_cholesky_decomp (a);
	}

	c_linalg_cholesky_decomp (l);
	info = c_linalg_cholesky_1down (l, u);
	c_matrix_sub (a, l);
	c_matrix_free (l);

	nrm = c_matrix_nrm (a, '1');
	c_matrix_free (a);

	return (info == 0 && nrm < 1.e-8);
}
Esempio n. 14
0
int main()
{
    disable_sigint();

    std::random_device rnd_device;
    std::mt19937 mersenne_engine(rnd_device());
    std::uniform_int_distribution<size_t> dist(1, 20);

    auto gen = std::bind(dist, mersenne_engine);

    size_t i = 0;
    for (;;)
    {
        if ((i % (16 * 1024)) == 0)
        {
            if (is_sigint_pending())
                break;
            std::cout << '.' << std::flush;
        }

        size_t size = gen();
        std::vector<char> input = random_vector(size, mersenne_engine);
        /*write_string_screened(std::cout, std::string(input.begin(), input.end()));
        std::cout << std::endl;*/

        input.push_back(guard_value);

        lexer lex(input.data(), input.data() + input.size() - 1);
        token tok = lex.fetch(true);
        for (;;)
        {
            if (tok.tok_type == token_type::eof)
                break;

            tok = lex.fetch(false);
        }

        ++i;
    }

    std::cout << "run " << i << " times\n";
}
Esempio n. 15
0
int main(void)
{
    std::cout << random_vector(8) << '\n';

    auto gen = std::bind(std::normal_distribution<double>{15,5.0},
                         std::default_random_engine{});

    std::vector<int> hist(2*15);
    for(size_t i{}; i<800; ++i)
        ++hist[static_cast<int>(std::round(gen()))];

    for(size_t i{}; i!=hist.size(); ++i){
        std::cout << i << '\t';
        for(ssize_t j{}; j!=hist[i]; ++j)
            std::cout << '*';
        std::cout << '\n';
    }

    return 0;
}
Esempio n. 16
0
void Scene::sign_distance_function(const Tree& tree)
{
    typedef typename Tree::size_type size_type;
    Vector random_vec = random_vector();

    for(int i=0 ; i<m_grid_size ; ++i)
    {
        for(int j=0 ; j<m_grid_size ; ++j)
        {
            const Point& p = m_distance_function[i][j].first;
            const FT unsigned_distance = m_distance_function[i][j].second;

            // get sign through ray casting (random vector)
            Ray ray(p, random_vec);
            size_type nbi = tree.number_of_intersected_primitives(ray);

            FT sign ( (nbi&1) == 0 ? 1 : -1);
            m_distance_function[i][j].second = sign * unsigned_distance;
        }
    }
}
Esempio n. 17
0
void Scene::generate_inside_points(const unsigned int nb_points)
{
    if(m_pPolyhedron == NULL)
    {
        std::cout << "Load polyhedron first." << std::endl;
        return;
    }

    typedef CGAL::AABB_face_graph_triangle_primitive<Polyhedron> Primitive;
    typedef CGAL::AABB_traits<Kernel, Primitive> Traits;
    typedef CGAL::AABB_tree<Traits> Tree;

    std::cout << "Construct AABB tree...";
    Tree tree(m_pPolyhedron->facets_begin(),m_pPolyhedron->facets_end(),*m_pPolyhedron);
    std::cout << "done." << std::endl;

    CGAL::Timer timer;
    timer.start();
    std::cout << "Generate " << nb_points << " inside points";

    unsigned int nb_trials = 0;
    Vector vec = random_vector();
    while(m_points.size() < nb_points)
    {
        Point p = random_point(tree.bbox());
        Ray ray(p,vec);
        int nb_intersections = (int)tree.number_of_intersected_primitives(ray);
        if(nb_intersections % 2 != 0)
        {
            m_points.push_back(p);
            if(m_points.size()%(nb_points/10) == 0)
                std::cout << "."; // ASCII progress bar
        }
        nb_trials++;
    }
    double speed = (double)nb_trials / timer.time();
    std::cout << "done (" << nb_trials << " trials, "
              << timer.time() << " s, "
              << speed << " queries/s)" << std::endl;
}
Esempio n. 18
0
static void test_set_extend(uint32_t size1, uint32_t size2) {
  uint32_t *bv1, *bv2;
  uint32_t i, w1, w2;

  assert(size1 >= size2);

  w1 = (size1 + 31) >> 5;
  w2 = (size2 + 31) >> 5;

  bv1 = bvconst_alloc(w1);
  bv2 = bvconst_alloc(w2);

  printf("=== test_set_extend: size1 = %"PRIu32", size2 = %"PRIu32" ===\n", size1, size2);

  for (i=0; i<20; i++) {
    random_vector(vector, size2);
    bvconst_set_array(bv2, vector, size2);

    printf("%"PRIu32" to %"PRIu32" bits\n", size2, size1);
    printf("bv2            = ");
    bvconst_print(stdout, bv2, size2);
    printf("\n");
    bvconst_set_extend(bv1, size1, bv2, size2, 0);
    printf("ext(bv2, %"PRIu32", 0) = ", size1);
    bvconst_print(stdout, bv1, size1);
    printf("\n");
    bvconst_set_extend(bv1, size1, bv2, size2, 1);
    printf("ext(bv2, %"PRIu32", 1) = ", size1);
    bvconst_print(stdout, bv1, size1);
    printf("\n");
    bvconst_set_extend(bv1, size1, bv2, size2, -1);
    printf("sgnext(bv2, %"PRIu32", 0) = ", size1);
    bvconst_print(stdout, bv1, size1);
    printf("\n\n");
  }

  printf("===\n");
  bvconst_free(bv1, w1);
  bvconst_free(bv2, w2);
}
Esempio n. 19
0
/* check |x - (l' * l)^-1 * y| < 1.e-8 */
bool
test_cholesky_svx (void)
{
	c_matrix	*a;
	c_vector	*x;
	c_vector	*y;

	c_matrix	*l;
	double		nrm;

	/* posdef symmetry matrix *a */
	{
		int			i;
		c_matrix	*a0 = random_matrix (size1, size1);
		a = c_matrix_transpose_dot_matrix (1., a0, a0);
		for (i = 0; i < size1; i++) c_matrix_set (a, i, i, c_matrix_get(a, i, i) + 0.1);
		c_matrix_free (a0);
	}
	/* vector *x */
	x = random_vector (size1);

	/* vector *y */
	y = c_matrix_dot_vector (1., a, x);

	/* cholesky_svx */
	c_linalg_cholesky_decomp (a);
	c_linalg_cholesky_svx (a, y);
	c_matrix_free (a);

	/* x = - y + x */
	c_vector_axpy (-1., y, x);
	c_vector_free (y);
	nrm = c_vector_nrm (x);
	c_vector_free (x);

	return (nrm < 1.e-8);
}
Esempio n. 20
0
/// Tests:
///  - storage_reader::size() const
///  - storage_reader::read(pointer, uint32_t, uint32_t)
TEST(TestStorageReader, test_storage_reader)
{
    uint32_t data_size = 1000;

    std::vector<uint8_t> data = random_vector(data_size);
    sak::const_storage data_storage = sak::storage(data);

    kodo::storage_reader<dummy_encoder> reader(data_storage);

    EXPECT_EQ(reader.size(), data_size);

    auto encoder = boost::make_shared<dummy_encoder>();

    reader.read(encoder, 10U, 10U);

    EXPECT_EQ(encoder->m_bytes_used, 10U);
    EXPECT_TRUE(sak::equal(encoder->m_symbol_storage,
                           sak::storage(&data[10], 10U)));

    reader.read(encoder, 57U, 101U);

    EXPECT_EQ(encoder->m_bytes_used, 101U);
    EXPECT_TRUE(sak::equal(encoder->m_symbol_storage,
                           sak::storage(&data[57], 101U)));

    // Try with some random values
    uint32_t random_offset = rand_nonzero(data_size - 1);
    uint32_t random_size = rand_nonzero(data_size - random_offset);

    reader.read(encoder, random_offset, random_size);

    EXPECT_EQ(encoder->m_bytes_used, random_size);
    EXPECT_TRUE(sak::equal(encoder->m_symbol_storage,
                           sak::storage(&data[random_offset], random_size)));

}
Esempio n. 21
0
int main() {
  const double RScale = 0.1;
  const double AScale = 1.0;
  const double IScale = 1e-2;
  const double MScale = 1.0;
  const double tVScale = 1.0;
  const double kScale = 0.1;

  const double eps = 1e-12;

  gsl_rng *rng;

  double SpinSun[3];
  double tVSun, kSun, ISun, MSun, RSun;

  double zerov[3] = {0.0, 0.0, 0.0};

  body b;
  central_body bc;

  double n;
  double a2;
  double adot;
  double ndot;
  double mu;

  double body_rhs[BODY_VECTOR_SIZE];
  double sun_rhs[3];

  double Ldot[3], hdot[3], bLdot[3], sLdot[3];

  int i;

  rng = gsl_rng_alloc(gsl_rng_ranlxd2);
  assert(rng);

  seed_random(rng);

  init_body_from_elements(&b, MScale*gsl_rng_uniform(rng), AScale*gsl_rng_uniform(rng), gsl_rng_uniform(rng),
                          180.0*gsl_rng_uniform(rng), 360.0*gsl_rng_uniform(rng), 360.0*gsl_rng_uniform(rng), 
                          zerov, tVScale*gsl_rng_uniform(rng), kScale*gsl_rng_uniform(rng), 
                          IScale*gsl_rng_uniform(rng), RScale*gsl_rng_uniform(rng));

  random_vector(rng, b.spin, 1.0);
  random_vector(rng, SpinSun, 1.0);
  
  tVSun = tVScale*gsl_rng_uniform(rng);
  kSun = kScale*gsl_rng_uniform(rng);
  ISun = IScale*gsl_rng_uniform(rng);
  RSun = RScale*gsl_rng_uniform(rng);

  init_central_body(&bc, tVSun, kSun, ISun, RSun, SpinSun);

  tidal_rhs(&b, &bc, body_rhs, sun_rhs);

  n = mean_motion(&b);
  a2 = b.a*b.a;

  adot = body_rhs[BODY_a_INDEX];
  ndot = -3.0/2.0*adot/b.a*n;

  mu = b.m/(1.0+b.m);

  for (i = 0; i < 3; i++) {
    hdot[i] = mu*n*a2*(body_rhs[BODY_L_INDEX+i] + 0.5*(adot/b.a)*b.L[i]);
    bLdot[i] = b.I*body_rhs[BODY_SPIN_INDEX+i];
    sLdot[i] = ISun*sun_rhs[i];
    Ldot[i] = hdot[i] + bLdot[i] + sLdot[i];
  }

  if (!check_close(eps, eps, norm(Ldot), 0.0)) {
    fprintf(stderr, "Ldot = {%g, %g, %g} not close to zero!\n",
            Ldot[0], Ldot[1], Ldot[2]);
    fprintf(stderr, "mu*hdot = {%g, %g, %g}\n", hdot[0], hdot[1], hdot[2]);
    fprintf(stderr, "Body LDot = {%g, %g, %g}\n", bLdot[0], bLdot[1], bLdot[2]);
    fprintf(stderr, "Sun  LDot = {%g, %g, %g}\n", sLdot[0], sLdot[1], sLdot[2]);
    gsl_rng_free(rng);
    exit(1);
  }

  if (!check_close(eps, eps, dot(b.L, body_rhs + BODY_L_INDEX) + dot(b.A, body_rhs + BODY_A_INDEX), 0.0)) {
    fprintf(stderr, "A^2 + L^2 = 1.0 magnitude constraint violated!\n");
    exit(1);
  }

  if (!check_close(eps, eps, dot(b.L, body_rhs + BODY_A_INDEX) + dot(b.A, body_rhs + BODY_L_INDEX), 0.0)) {
    fprintf(stderr, "A*L = 0 constraint violated!\n");
    exit(1);
  }

  gsl_rng_free(rng);
  return 0;
}
Esempio n. 22
0
c_vector<double, SPACE_DIM> OffLatticeSimulation<ELEMENT_DIM,SPACE_DIM>::CalculateCellDivisionVector(CellPtr pParentCell)
{
    /**
     * \todo #2400 Could remove this dynamic_cast by moving the code block below into
     * AbstractCentreBasedCellPopulation::AddCell(), allowing it to be overruled by
     * this method when overridden in subclasses. See also comment on #1093.
     */
    // If it is not vertex based...
    if (dynamic_cast<AbstractCentreBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>*>(&(this->mrCellPopulation)))
    {
        // Location of parent and daughter cells
        c_vector<double, SPACE_DIM> parent_coords = this->mrCellPopulation.GetLocationOfCellCentre(pParentCell);
        c_vector<double, SPACE_DIM> daughter_coords;

        // Get separation parameter
        double separation = static_cast<AbstractCentreBasedCellPopulation<ELEMENT_DIM,SPACE_DIM>*>(&(this->mrCellPopulation))->GetMeinekeDivisionSeparation();

        // Make a random direction vector of the required length
        c_vector<double, SPACE_DIM> random_vector;

        /*
         * Pick a random direction and move the parent cell backwards by 0.5*separation
         * in that direction and return the position of the daughter cell 0.5*separation
         * forwards in that direction.
         */
        switch (SPACE_DIM)
        {
            case 1:
            {
                double random_direction = -1.0 + 2.0*(RandomNumberGenerator::Instance()->ranf() < 0.5);

                random_vector(0) = 0.5*separation*random_direction;
                break;
            }
            case 2:
            {
                double random_angle = 2.0*M_PI*RandomNumberGenerator::Instance()->ranf();

                random_vector(0) = 0.5*separation*cos(random_angle);
                random_vector(1) = 0.5*separation*sin(random_angle);
                break;
            }
            case 3:
            {
                /*
                 * Note that to pick a random point on the surface of a sphere, it is incorrect
                 * to select spherical coordinates from uniform distributions on [0, 2*pi) and
                 * [0, pi) respectively, since points picked in this way will be 'bunched' near
                 * the poles. See #2230.
                 */
                double u = RandomNumberGenerator::Instance()->ranf();
                double v = RandomNumberGenerator::Instance()->ranf();

                double random_azimuth_angle = 2*M_PI*u;
                double random_zenith_angle = std::acos(2*v - 1);

                random_vector(0) = 0.5*separation*cos(random_azimuth_angle)*sin(random_zenith_angle);
                random_vector(1) = 0.5*separation*sin(random_azimuth_angle)*sin(random_zenith_angle);
                random_vector(2) = 0.5*separation*cos(random_zenith_angle);
                break;
            }
            default:
                // This can't happen
                NEVER_REACHED;
        }

        parent_coords = parent_coords - random_vector;
        daughter_coords = parent_coords + random_vector;

        // Set the parent to use this location
        ChastePoint<SPACE_DIM> parent_coords_point(parent_coords);
        unsigned node_index = this->mrCellPopulation.GetLocationIndexUsingCell(pParentCell);
        this->mrCellPopulation.SetNode(node_index, parent_coords_point);

        return daughter_coords;
    }
    else
    {
        // Check this is a Vertex based cell population (in case new types are added later!).
        assert(dynamic_cast<VertexBasedCellPopulation<SPACE_DIM>*>(&(this->mrCellPopulation)));

        VertexBasedCellPopulation<SPACE_DIM>* p_vertex_population = dynamic_cast<VertexBasedCellPopulation<SPACE_DIM>*>(&(this->mrCellPopulation));
        boost::shared_ptr<AbstractVertexBasedDivisionRule<SPACE_DIM> > p_division_rule = p_vertex_population->GetVertexBasedDivisionRule();

        return p_division_rule->CalculateCellDivisionVector(pParentCell, *p_vertex_population);
    }
}
Esempio n. 23
0
 Point getLightSample() {
   return Point(random_vector() * radius);
 }
Esempio n. 24
0
Plane Scene::random_plane(const CGAL::Bbox_3& bbox)
{
    Point p = random_point(bbox);
    Vector vec = random_vector();
    return Plane(p,vec);
}
int main(int argc, char *argv[]){
      char output[COMMAND_LEN]="";
      char last_output[COMMAND_LEN]="";		 
      char msg[MSG];
      int pad=0;
      int reads=0;
      int sock_atropos=0;
      int encendido=0;
      int gas=0;
      int alabeo=0;
      int cabeceo=0;
      int guinnada=0;
      int pipe_des[2];	
      char com[20]="";
      int analog=0;
      char conectado=0;
      int rounds=0;
      int alive=0;
      int ispresent=0;
      char * ptok;
      int out_gas;
      int last_gas;
      int send_gas=0;
      int send_guinnada=0;
      int ignore_round=0;
      int transient_present=0;
      int config=0;
      char device[100]="wlan0";
      int result=0;
      char errorBuffer[PCAP_ERRBUF_SIZE];

      char mode_send=MODE_SEND;

      const u_char *pkt_data;
      struct pcap_pkthdr *header;

	printf("\r\nEMISORA INTERCEPTOR\n\n");
      

      if(argc>1){
        if (argv[1][0]=='#'){
	        strcpy(my_str_conn,&argv[1][1]);
            if (argc>2){strcpy(device,argv[1]);}

        }else{
            strcpy(device,argv[1]);
	    if(argc>=2){
		strcpy(stage, argv[2]);
		if(argc>=3){
			mode_send=argv[3][0];
		}
	    }
        }
	

      }

	struct sched_param schedule;

	schedule.sched_priority=sched_get_priority_min(SCHED_OTHER);
	sched_setscheduler(pthread_self(), SCHED_OTHER,&schedule);	

	schedule.sched_priority=sched_get_priority_min(SCHED_FIFO);
	sched_setscheduler(pthread_self(), SCHED_FIFO,&schedule);

    
    printf("\nSTAGE %s", stage);
    printf("\nMODE  %c", mode_send);
     

    char log_file_path[128]="";
    int hastolog=0;
    FILE *fl;
    fl = fopen(LOG_FILE_TARGET, "r");

    if (fl!=NULL){

	int readp=fread(log_file_path,sizeof(char),128,fl);
	log_file_path[readp-1]='\0';
	fclose(fl);
        fl=fopen(log_file_path,"w+");
        if(fl!=NULL){hastolog=1; printf("\nLOG DE QUERY ACTIVADO");}
	
    }

    printf("\nLOG STATUS %i  %s ", hastolog, log_file_path);


    if(mode_send!='F'){

	    pcap_if_t * allAdapters;
	    pcap_if_t * adapter;  
	    printf("\nABRIENDO PCAP");
	    fflush(stdout);
	    result= pcap_findalldevs(&allAdapters, errorBuffer );
	    printf("\nRespuesta PCAP: %i\n", result);
	    fflush(stdout);
	    if(result==0){
		
		for( adapter = allAdapters; adapter != NULL; adapter = adapter->next)
		{
		        //printf("\r\nDetectando %s", adapter->name);
		        if (strcmp(adapter->name, device)==0){
	   		    rfmon_avail=1;                 
		            break;
		        }
		        
		}
	    }


	    if(rfmon_avail){
		init_gcrypt(&gcry_hd);

	    	seq=1;

	    	printf("\nInterfaz en RFMON cargada: %s",adapter->name );
	    	capture = pcap_open_live(device, BUFSIZ, 1, 1000, errorBuffer);
	       

	    	printf("\nResultado: %s\n",pcap_geterr(capture));      
	    	if(capture==NULL){printf("\n NULL HANDLER");}
	    
	   }else{
		printf("\nADVERTENCIA: Sin soporte con RFMON");
	
	   }
   } 
    printf("\nAbriendo entrenador");

    pad=open(CONTROL_DEVICE,O_RDONLY|O_NONBLOCK);
    char input='n';
     if(pad<=0){
        printf("\nNo se encuentran mandos. Continuar?[s/N]:");
	scanf ("%c",&input);
        if(input!='s'){
                exit(-1);
        }
    }else{
    conectado=1;
    }
    conectado=1;



    printf("\nEntrenador en #%i\n",pad);
    encendido=0;
  
    ispresent=1;
    last_gas=20000;
       if(hastolog==1){	
		sprintf(output, "QQZ%iZ0Z0Z0Z", last_gas);	
		printf("\n ESCRITO PRIMER LOG %i",fprintf(fl,"%s\n", output ));
		fflush(fl);
       } 
	if (mode_send!='F'){
		if ((stage[0]=='S')||(stage[0]=='N')){	
			printf("\nGENERANDO CLAVE");	
			random_vector(gcry_key,GCRY_KEYLEN);		
		}
		if(stage[0]=='K'){
			
			int loadkey=load_key_from_file(gcry_key);
			printf("\nCARGADA CLAVE: %i", loadkey);
			if(loadkey!=0){exit(-1);}
		}else{
			while(notify_key_to_rfmon(gcry_key)!=0){
				printf("\nKEY EXANGE FAILED, RETRY");
				sleep(1);
			}
		}
		 printf("\r\n KEY EXANGE OK");
		if (stage[0]=='S'){
			printf("\nETAPA GENERAR CLAVE HECHO");
			exit(0);
		}      
	        if(rfmon_avail){
			gcry_cipher_setkey (gcry_hd,gcry_key,GCRY_KEYLEN);
	        } 
      }


    while(1==1){
	
    reads=read(pad,msg,MSG);

    if(rfmon_avail==0){mode_send='F';}

    if (reads==MSG){
        alive=0;
        encendido=1; 
        analog=msg[5];	
        //printf("\r\n%i ANALOG %i",msg[7], analog);	
        if((msg[7]==2)&&(encendido==1)){//gas
            gas=((analog+127))*GAS_FACTOR;
          if((abs(gas-send_gas)<100000000)||((gas<228600000)&&(gas>20000))||(transient_present==1)){
		    //printf("\r\n!GAS_SPIKE! %i",abs(gas-last_gas));
            //send_gas=gas;  
            transient_present=0;
           send_gas=gas;

	    }
#ifndef MANDO_ABORDO
		else{
	
            printf("!");

            }
#endif          
          
        }
        if((msg[7]==4)&&(encendido==1)){//guiñada
          guinnada=-analog*GUINNADA_FACTOR;
        }
        if((msg[7]==1)&&(encendido==1)){//cabeceo
          cabeceo=-analog*CABECEO_FACTOR;
        }
        if((msg[7]==0)&&(encendido==1)){//alabeo
          alabeo=-analog*ALABEO_FACTOR;
        }  
        conectado=1;   
    }else{
        alive++;
    }
    if(alive>=2000){
        alive=0;
        close(pad);
        if(ispresent==0){
            transient_present=1;
        }
        ispresent=1;
        pad=open(CONTROL_DEVICE,O_RDONLY|O_NONBLOCK);
        if( access( CONTROL_DEVICE, R_OK ) < 0 ) {
            ispresent=0;
        }
    }
    rounds++;


    if((encendido==1)&&(conectado==1)&&(ispresent==1)&&(rounds>=ROUND_WINDOW)){
       
	    if((send_gas<=GAS_CONFIG)&&(guinnada==0)){
		    config=1;

	    }
	    if(send_gas>GAS_CONFIG){config=0;}
	    if (config==1){
		    send_guinnada=0;
                      // printf("\r\n %i %i ", guinnada,STOP_WITH_YAW);
                        if(guinnada<=STOP_WITH_YAW){
                                query("Y0                         ",mode_send);
				
                        }
                        if(guinnada>=START_WITH_YAW){
				if((rfmon_avail)&&(1==2)){
					random_vector(gcry_key,GCRY_KEYLEN);
					gcry_cipher_setkey (gcry_hd,gcry_key,GCRY_KEYLEN);
    					seq=2;				
					notify_key_to_rfmon(gcry_key);
				}
	                        query("Y1000000                   ",mode_send);
				

			
                        }
			if(hastolog==1){fflush(fl);}
	    }else{
            send_guinnada=guinnada;
        }
	
	
	    sprintf(output, "QQZ%iZ%iZ%iZ%iZ", (int)send_gas/1000,(int)alabeo/1000, (int)cabeceo/1000, (int)send_guinnada/1000);

	    if(hastolog==1){
		fprintf(fl,"%s\n", output );
             }
		
		printf(".");fflush(stdout);
	    query(output, mode_send);
        rounds=0;

    }
    
    //#ifndef MANDO_ABORDO
	usleep(500);
    //#endif

    

    }   
}
static int
authenticate(int sockfd, const char *username, const char *passwd)
{
    AUTH_HDR *auth;
    u_short total_length;
    u_char *ptr;
    int length;
    char passbuf[MAXPASS];
    u_char md5buf[256];
    int secretlen;
    u_char cbc[AUTH_VECTOR_LEN];
    int i, j;
    u_int32_t ui;
    struct sockaddr_in saremote;
    fd_set readfds;
    socklen_t salen;
    int retry = retries;

    /*
     *    Build an authentication request
     */
    auth = (AUTH_HDR *) send_buffer;
    auth->code = PW_AUTHENTICATION_REQUEST;
    auth->id = ++request_id;
    random_vector(vector);
    memcpy(auth->vector, vector, AUTH_VECTOR_LEN);
    total_length = AUTH_HDR_LEN;
    ptr = auth->data;

    /*
     *    User Name
     */
    *ptr++ = PW_USER_NAME;
    length = strlen(username);
    if (length > MAXPWNAM) {
	length = MAXPWNAM;
    }
    *ptr++ = length + 2;
    memcpy(ptr, username, length);
    ptr += length;
    total_length += length + 2;

    /*
     *    Password
     */
    length = strlen(passwd);
    if (length > MAXPASS) {
	length = MAXPASS;
    }
    memset(passbuf, 0, MAXPASS);
    memcpy(passbuf, passwd, length);

    /* 
     * Length is rounded up to multiple of 16,
     * and the password is encoded in blocks of 16 
     * with cipher block chaining
     */
    length = ((length / AUTH_VECTOR_LEN) + 1) * AUTH_VECTOR_LEN;

    *ptr++ = PW_PASSWORD;
    *ptr++ = length + 2;

    secretlen = strlen(secretkey);
    /* Set up the Cipher block chain */
    memcpy(cbc, auth->vector, AUTH_VECTOR_LEN);
    for (j = 0; j < length; j += AUTH_VECTOR_LEN) {
	/* Calculate the MD5 Digest */
	strcpy((char *)md5buf, secretkey);
	memcpy(md5buf + secretlen, cbc, AUTH_VECTOR_LEN);
	md5_calc(cbc, md5buf, secretlen + AUTH_VECTOR_LEN);

	/* Xor the password into the MD5 digest */
	for (i = 0; i < AUTH_VECTOR_LEN; i++) {
	    *ptr++ = (cbc[i] ^= passbuf[j + i]);
	}
    }
    total_length += length + 2;

    *ptr++ = PW_NAS_PORT_ID;
    *ptr++ = 6;

    ui = htonl(nasport);
    memcpy(ptr, &ui, 4);
    ptr += 4;
    total_length += 6;

    *ptr++ = PW_NAS_PORT_TYPE;
    *ptr++ = 6;

    ui = htonl(nasporttype);
    memcpy(ptr, &ui, 4);
    ptr += 4;
    total_length += 6;

    if (*identifier) {
	int len = strlen(identifier);
	*ptr++ = PW_NAS_ID;
	*ptr++ = len + 2;
	memcpy(ptr, identifier, len);
	ptr += len;
    } else {
	*ptr++ = PW_NAS_IP_ADDRESS;
	*ptr++ = 6;

	ui = htonl(nas_ipaddr);
	memcpy(ptr, &ui, 4);
	ptr += 4;
	total_length += 6;
    }

    /* Klaus Weidner <*****@*****.**> changed this
     * from htonl to htons. It might have caused
     * you trouble or not. That depends on the byte
     * order of your system.
     * The symptom was that the radius server
     * ignored the requests, because they had zero 
     * length according to the data header.
     */
    auth->length = htons(total_length);

    while(retry--) {
	int time_spent;
	struct timeval sent;
	/*
	 *    Send the request we've built.
	 */
	gettimeofday(&sent, NULL);
	send(sockfd, (char *) auth, total_length, 0);
	while ((time_spent = time_since(&sent)) < 1000000) {
	    struct timeval tv;
	    int rc, len;
	    if (!time_spent) {
		tv.tv_sec = 1;
		tv.tv_usec = 0;
	    } else {
		tv.tv_sec = 0;
		tv.tv_usec = 1000000 - time_spent;
	    }
	    FD_ZERO(&readfds);
	    FD_SET(sockfd, &readfds);
	    if (select(sockfd + 1, &readfds, NULL, NULL, &tv) == 0)	/* Select timeout */
		break;
	    salen = sizeof(saremote);
	    len = recvfrom(sockfd, recv_buffer, sizeof(i_recv_buffer),
		0, (struct sockaddr *) &saremote, &salen);

	    if (len < 0)
		continue;

	    rc = result_recv(saremote.sin_addr.s_addr, saremote.sin_port, recv_buffer, len);
	    if (rc == 0)
		return 1;
	    if (rc == 1)
	    	return 0;
	}
    }

    fprintf(stderr, "%s: No response from RADIUS server\n", progname);

    return 0;
}
Esempio n. 27
0
void SGVector<T>::random(T min_value, T max_value)
{
	random_vector(vector, vlen, min_value, max_value);
}
Esempio n. 28
0
void run_test_random_annex_partial(uint32_t max_symbols,
                                 uint32_t max_symbol_size,
                                 uint32_t multiplier)
{

    uint32_t object_size = max_symbols * max_symbol_size * multiplier;
    object_size -= (rand() % object_size);

    uint32_t annex_size = kodo::max_annex_size(
        max_symbols, max_symbol_size, object_size);

    if(annex_size > 0)
    {
        // Randomize the actual annex size
        annex_size -= (rand() % annex_size);
    }

    typedef kodo::random_annex_encoder<Encoder, Partitioning>
        random_annex_encoder;

    typedef kodo::random_annex_decoder<Decoder, Partitioning>
        random_annex_decoder;

    std::vector<uint8_t> data_in = random_vector(object_size);
    std::vector<uint8_t> data_out(object_size, '\0');

    typename Encoder::factory encoder_factory(max_symbols, max_symbol_size);
    typename Decoder::factory decoder_factory(max_symbols, max_symbol_size);

    random_annex_encoder obj_encoder(
        annex_size, encoder_factory, sak::storage(data_in));

    random_annex_decoder obj_decoder(
        annex_size, decoder_factory, obj_encoder.object_size());

    EXPECT_TRUE(obj_encoder.encoders() >= 1);
    EXPECT_TRUE(obj_decoder.decoders() >= 1);
    EXPECT_TRUE(obj_encoder.encoders() == obj_decoder.decoders());

    uint32_t bytes_used = 0;

    for(uint32_t i = 0; i < obj_encoder.encoders(); ++i)
    {
        auto encoder = obj_encoder.build(i);
        typename random_annex_decoder::pointer_type decoder =
            obj_decoder.build(i);

        if(kodo::has_systematic_encoder<Encoder>::value)
            kodo::set_systematic_off(encoder);

        EXPECT_TRUE(encoder->block_size() >= encoder->bytes_used());
        EXPECT_TRUE(decoder->block_size() >= decoder->bytes_used());

        EXPECT_TRUE(encoder->block_size() == decoder->block_size());
        EXPECT_TRUE(encoder->bytes_used() == decoder->bytes_used());
        EXPECT_TRUE(encoder->payload_size() == decoder->payload_size());

        std::vector<uint8_t> payload(encoder->payload_size());

        while(!decoder->is_complete())
        {
            encoder->encode( &payload[0] );
            decoder->decode( &payload[0] );
        }

        sak::mutable_storage storage = sak::storage(
            &data_out[0] + bytes_used, decoder->bytes_used());

        decoder.unwrap()->copy_symbols(storage);

        bytes_used += decoder->bytes_used();
    }

    EXPECT_EQ(bytes_used, object_size);
    EXPECT_TRUE(std::equal(data_in.begin(),
                           data_in.end(),
                           data_out.begin()));

}
Esempio n. 29
0
inline void test_basic_api(uint32_t symbols, uint32_t symbol_size)
{

    // Common setting
    typename Encoder::factory encoder_factory(symbols, symbol_size);
    auto encoder = encoder_factory.build();

    typename Decoder::factory decoder_factory(symbols, symbol_size);
    auto decoder = decoder_factory.build();

    EXPECT_TRUE(symbols == encoder_factory.max_symbols());
    EXPECT_TRUE(symbol_size == encoder_factory.max_symbol_size());
    EXPECT_TRUE(symbols == encoder->symbols());
    EXPECT_TRUE(symbol_size == encoder->symbol_size());

    EXPECT_TRUE(symbols == decoder_factory.max_symbols());
    EXPECT_TRUE(symbol_size == decoder_factory.max_symbol_size());
    EXPECT_TRUE(symbols == decoder->symbols());
    EXPECT_TRUE(symbol_size == decoder->symbol_size());

    EXPECT_TRUE(encoder->symbol_length() > 0);
    EXPECT_TRUE(decoder->symbol_length() > 0);

    EXPECT_TRUE(encoder->block_size() == symbols * symbol_size);
    EXPECT_TRUE(decoder->block_size() == symbols * symbol_size);

    EXPECT_TRUE(encoder_factory.max_payload_size() >=
                encoder->payload_size());

    EXPECT_TRUE(decoder_factory.max_payload_size() >=
                decoder->payload_size());

    EXPECT_EQ(encoder_factory.max_payload_size(),
              decoder_factory.max_payload_size());

    // Encode/decode operations
    EXPECT_EQ(encoder->payload_size(), decoder->payload_size());

    std::vector<uint8_t> payload(encoder->payload_size());

    std::vector<uint8_t> data_in = random_vector(encoder->block_size());
    std::vector<uint8_t> data_in_copy(data_in);

    sak::mutable_storage storage_in = sak::storage(data_in);
    sak::mutable_storage storage_in_copy = sak::storage(data_in_copy);

    EXPECT_TRUE(sak::equal(storage_in, storage_in_copy));

    // Only used for prime fields, lets reconsider how we implement
    // this less intrusive
    uint32_t prefix = 0;

    if(fifi::is_prime2325<typename Encoder::field_type>::value)
    {
        // This field only works for multiple of uint32_t
        assert((encoder->block_size() % 4) == 0);

        uint32_t block_length = encoder->block_size() / 4;

        fifi::prime2325_binary_search search(block_length);
        prefix = search.find_prefix(storage_in_copy);

        // Apply the negated prefix
        fifi::apply_prefix(storage_in_copy, ~prefix);
    }

    encoder->set_symbols(storage_in_copy);

    // Set the encoder non-systematic
    if(kodo::is_systematic_encoder(encoder))
        kodo::set_systematic_off(encoder);

    while( !decoder->is_complete() )
    {
        uint32_t payload_used = encoder->encode( &payload[0] );
        EXPECT_TRUE(payload_used <= encoder->payload_size());

        decoder->decode( &payload[0] );
    }

    std::vector<uint8_t> data_out(decoder->block_size(), '\0');
    decoder->copy_symbols(sak::storage(data_out));

    if(fifi::is_prime2325<typename Encoder::field_type>::value)
    {
        // Now we have to apply the negated prefix to the decoded data
        fifi::apply_prefix(sak::storage(data_out), ~prefix);
    }

    EXPECT_TRUE(std::equal(data_out.begin(),
                           data_out.end(),
                           data_in.begin()));
}
Esempio n. 30
0
int main() {
  int32_t i, j, n;

  alloc_constants();

  printf("a = ");
  bvconst_print(stdout, a, 128);
  printf("\n");
  printf("iszero(a) = %d\n", bvconst_is_zero(a, 4));

  bvconst_add_one(a, 4);
  printf("a+1 = ");
  bvconst_print(stdout, a, 128);
  printf("\n");
  printf("iszero(a+1) = %d\n", bvconst_is_zero(a, 4));

  bvconst_sub_one(a, 4);
  printf("a+1-1 = ");
  bvconst_print(stdout, a, 128);
  printf("\n");
  printf("iszero(a+1-1) = %d\n", bvconst_is_zero(a, 4));

  bvconst_sub_one(a, 4);
  printf("a+1-2 = ");
  bvconst_print(stdout, a, 128);
  printf("\n");
  printf("iszero(a+1-2) = %d\n", bvconst_is_zero(a, 4));


  printf("b = ");
  bvconst_print(stdout, b, 128);
  printf("\n");
  printf("iszero(b) = %d\n", bvconst_is_zero(b, 4));

  bvconst_add_one(b, 4);
  printf("b+1 = ");
  bvconst_print(stdout, b, 128);
  printf("\n");
  printf("iszero(b+1) = %d\n", bvconst_is_zero(b, 4));

  bvconst_sub_one(b, 4);
  bvconst_sub_one(b, 4);
  printf("b-1 = ");
  bvconst_print(stdout, b, 128);
  printf("\n");
  printf("iszero(b-1) = %d\n", bvconst_is_zero(b, 4));


  printf("c = ");
  bvconst_print(stdout, c, 128);
  printf("\n");
  printf("iszero(c) = %d\n", bvconst_is_zero(c, 4));

  printf("d = ");
  bvconst_print(stdout, d, 128);
  printf("\n");
  printf("iszero(d) = %d\n", bvconst_is_zero(d, 4));

  printf("e = ");
  bvconst_print(stdout, e, 128);
  printf("\n");
  printf("iszero(e) = %d\n", bvconst_is_zero(e, 4));

  printf("e := a * b\n");
  bvconst_mul2(e, 4, a, b);
  printf("e = ");
  bvconst_print(stdout, e, 128);
  printf("\n\n");

  random_vector(vector, 32);
  bvconst_set_array(a, vector, 32);
  printf("a            = ");
  bvconst_print(stdout, a, 32);
  printf("\n");
  random_vector(vector, 73);
  bvconst_set_array(b, vector, 73);
  printf("b            = ");
  bvconst_print(stdout, b, 73);
  printf("\n");
  bvconst_concat(c, a, 32, b, 73);
  printf("conc(a, b)   = ");
  bvconst_print(stdout, c, 105);
  printf("\n");
  bvconst_concat(d, b, 73, a, 32);
  printf("conc(b, a)   = ");
  bvconst_print(stdout, d, 105);
  printf("\n\n");

  //  random_vector(vector, 63);
  bvconst_set_minus_one(a, 4);
  //  random_vector(vector, 63);
  bvconst_clear(b, 4);
  for (n=2; n<=128; n++) {
    for (i=1; i<n; i++) {
      printf("--- n = %"PRId32", i = %"PRId32" ---\n", n, i);
      printf("a          = ");
      bvconst_print(stdout, a, i);
      printf("\n");
      printf("b          = ");
      bvconst_print(stdout, b, n - i);
      printf("\n");
      bvconst_concat(c, a, i, b, n - i);
      bvconst_concat(d, b, n - i, a, i);
      printf("conc(a, b) = ");
      bvconst_print(stdout, c, n);
      printf("\n");
      printf("conc(b, a) = ");
      bvconst_print(stdout, d, n);
      printf("\n\n");
    }
  }


  //  exit(0);

  for (n=20; n>0; n--) {
    random_vector(vector, 20);
    bvconst_set_array(a, vector, 20);
    printf("a             = ");
    bvconst_print(stdout, a, 20);
    printf("\n");

    for (i=0; i<=20-n; i++) {
      bvconst_extract(b, a, i, i+n);
      printf("a[%2"PRId32", %2"PRId32")     = ", i, i+n);
      bvconst_print(stdout, b, n);
      printf("\n");
    }
    printf("\n");
  }


  for (n=50; n>20; n--) {
    random_vector(vector, 62);
    bvconst_set_array(a, vector, 62);
    printf("a             = ");
    bvconst_print(stdout, a, 62);
    printf("\n");

    for (i=0; i<=62-n; i++) {
      bvconst_extract(b, a, i, i+n);
      printf("a[%2"PRId32", %2"PRId32")     = ", i, i+n);
      bvconst_print(stdout, b, n);
      printf("\n");
    }
    printf("\n");
  }

  random_vector(vector, 20);
  bvconst_set_array(a, vector, 20);
  printf("a             = ");
  bvconst_print(stdout, a, 20);
  printf("\n");
  bvconst_set_extend(b, 31, a, 20, 0);
  printf("ext(a, 31, 0) = ");
  bvconst_print(stdout, b, 31);
  printf("\n");
  bvconst_set_extend(b, 31, a, 20, 1);
  printf("ext(a, 31, 1) = ");
  bvconst_print(stdout, b, 31);
  printf("\n");
  bvconst_set_extend(b, 31, a, 20, -1);
  printf("sgnext(a, 31) = ");
  bvconst_print(stdout, b, 31);
  printf("\n\n");


  random_vector(vector, 20);
  bvconst_set_array(a, vector, 20);
  printf("a             = ");
  bvconst_print(stdout, a, 20);
  printf("\n");
  bvconst_set_extend(b, 31, a, 20, 0);
  printf("ext(a, 31, 0) = ");
  bvconst_print(stdout, b, 31);
  printf("\n");
  bvconst_set_extend(b, 31, a, 20, 1);
  printf("ext(a, 31, 1) = ");
  bvconst_print(stdout, b, 31);
  printf("\n");
  bvconst_set_extend(b, 31, a, 20, -1);
  printf("sgnext(a, 31) = ");
  bvconst_print(stdout, b, 31);
  printf("\n\n");


  random_vector(vector, 20);
  bvconst_set_array(a, vector, 20);
  printf("a             = ");
  bvconst_print(stdout, a, 20);
  printf("\n");
  bvconst_set_extend(b, 31, a, 20, 0);
  printf("ext(a, 31, 0) = ");
  bvconst_print(stdout, b, 31);
  printf("\n");
  bvconst_set_extend(b, 31, a, 20, 1);
  printf("ext(a, 31, 1) = ");
  bvconst_print(stdout, b, 31);
  printf("\n");
  bvconst_set_extend(b, 31, a, 20, -1);
  printf("sgnext(a, 31) = ");
  bvconst_print(stdout, b, 31);
  printf("\n\n");


  random_vector(vector, 20);
  bvconst_set_array(a, vector, 20);
  printf("a             = ");
  bvconst_print(stdout, a, 20);
  printf("\n");
  bvconst_set_extend(b, 31, a, 20, 0);
  printf("ext(a, 31, 0) = ");
  bvconst_print(stdout, b, 31);
  printf("\n");
  bvconst_set_extend(b, 31, a, 20, 1);
  printf("ext(a, 31, 1) = ");
  bvconst_print(stdout, b, 31);
  printf("\n");
  bvconst_set_extend(b, 31, a, 20, -1);
  printf("sgnext(a, 31) = ");
  bvconst_print(stdout, b, 31);
  printf("\n\n");


  for (i=20; i<=99; i++) {
    random_vector(vector, 20);
    bvconst_set_array(a, vector, 20);
    printf("a             = ");
    bvconst_print(stdout, a, 20);
    printf("\n");
    bvconst_set_extend(b, i, a, 20, 0);
    printf("ext(a, %2"PRId32", 0) = ", i);
    bvconst_print(stdout, b, i);
    printf("\n");
    bvconst_set_extend(b, i, a, 20, 1);
    printf("ext(a, %2"PRId32", 1) = ", i);
    bvconst_print(stdout, b, i);
    printf("\n");
    bvconst_set_extend(b, i, a, 20, -1);
    printf("sgnext(a, %2"PRId32") = ", i);
    bvconst_print(stdout, b, i);
    printf("\n\n");
  }


  for (i=32; i<=99; i++) {
    random_vector(vector, 32);
    bvconst_set_array(a, vector, 32);
    printf("a             = ");
    bvconst_print(stdout, a, 32);
    printf("\n");
    bvconst_set_extend(b, i, a, 32, 0);
    printf("ext(a, %2"PRId32", 0) = ", i);
    bvconst_print(stdout, b, i);
    printf("\n");
    bvconst_set_extend(b, i, a, 32, 1);
    printf("ext(a, %2"PRId32", 1) = ", i);
    bvconst_print(stdout, b, i);
    printf("\n");
    bvconst_set_extend(b, i, a, 32, -1);
    printf("sgnext(a, %2"PRId32") = ", i);
    bvconst_print(stdout, b, i);
    printf("\n\n");
  }


  random_vector(vector, 120);
  bvconst_set_array(a, vector, 120);
  printf("a         = ");
  bvconst_print(stdout, a, 120);
  printf("\n");
  for (i=0; i<=120; i++) {
    printf("rshift %3"PRId32": ", i);
    bvconst_shift_right(a, 120, i, 0);
    bvconst_print(stdout, a, 120);
    printf("\n");
    bvconst_set_array(a, vector, 120);
  }
  printf("\n");

  random_vector(vector, 120);
  bvconst_set_array(a, vector, 120);
  printf("a         = ");
  bvconst_print(stdout, a, 120);
  printf("\n");
  for (i=0; i<=120; i++) {
    printf("rshift %3"PRId32": ", i);
    bvconst_shift_right(a, 120, i, 1);
    bvconst_print(stdout, a, 120);
    printf("\n");
    bvconst_set_array(a, vector, 120);
  }
  printf("\n");


  random_vector(vector, 120);
  bvconst_set_array(a, vector, 120);
  printf("a         = ");
  bvconst_print(stdout, a, 120);
  printf("\n");
  for (i=0; i<=120; i++) {
    printf("lshift %3"PRId32": ", i);
    bvconst_shift_left(a, 120, i, 0);
    bvconst_print(stdout, a, 120);
    printf("\n");
    bvconst_set_array(a, vector, 120);
  }
  printf("\n");

  random_vector(vector, 120);
  bvconst_set_array(a, vector, 120);
  printf("a         = ");
  bvconst_print(stdout, a, 120);
  printf("\n");
  for (i=0; i<=120; i++) {
    printf("lshift %3"PRId32": ", i);
    bvconst_shift_left(a, 120, i, 1);
    bvconst_print(stdout, a, 120);
    printf("\n");
    bvconst_set_array(a, vector, 120);
  }
  printf("\n");
  //  exit(0);


  printf("c = ");
  bvconst_print(stdout, c, 128);
  printf("\n");
  printf("d = ");
  bvconst_print(stdout, d, 128);
  printf("\n");
  printf("e := c * d\n");
  bvconst_mul2(e, 4, c, d);
  printf("e = ");
  bvconst_print(stdout, e, 128);
  printf("\n");
  printf("e := d * c\n");
  bvconst_mul2(e, 4, d, c);
  printf("e = ");
  bvconst_print(stdout, e, 128);
  printf("\n\n");

  printf("b = ");
  bvconst_print(stdout, b, 128);
  printf("\n");
  printf("d = ");
  bvconst_print(stdout, d, 128);
  printf("\n");
  printf("e := b * d\n");
  bvconst_mul2(e, 4, b, d);
  printf("e = ");
  bvconst_print(stdout, e, 128);
  printf("\n\n");



  bvconst_set64(a, 4, 1372919719782793ULL);
  bvconst_set32(b, 4, 12670371);
  printf("a = ");
  bvconst_print(stdout, a, 128);
  printf("\n");
  printf("b = ");
  bvconst_print(stdout, b, 128);
  printf("\n");
  printf("e := a * b\n");
  bvconst_set(c, 4, a);
  printf("c = ");
  bvconst_print(stdout, c, 128);
  printf("\n");
  bvconst_mul(c, 4, b);
  printf("c = ");
  bvconst_print(stdout, c, 128);
  printf("\n");
  bvconst_mul2(e, 4, a, b);
  printf("e = ");
  bvconst_print(stdout, e, 128);
  printf("\n\n");

  mpz_init(z0);
  mpz_init(z1);
  mpz_init(z2);

  bvconst_get_mpz(a, 4, z0);
  printf("--> conversion a to mpz: ");
  mpz_out_str(stdout, 10, z0);
  printf("\n");
  bvconst_get_mpz(b, 4, z0);
  printf("--> conversion b to mpz: ");
  mpz_out_str(stdout, 10, z0);
  printf("\n");
  bvconst_get_mpz(e, 4, z0);
  printf("--> conversion e to mpz: ");
  mpz_out_str(stdout, 10, z0);
  printf("\n\n");

  printf("e -= a * b\n");
  bvconst_submul(e, 4, a, b);
  printf("e = ");
  bvconst_print(stdout, e, 128);
  printf("\n");
  bvconst_get_mpz(e, 4, z0);
  printf("--> conversion e to mpz: ");
  mpz_out_str(stdout, 10, z0);
  printf("\n\n");

  for (i=0; i<10; i++) {
    printf("test %"PRId32": e *= a\n", i);
    random_vector(vector, 128);
    bvconst_set_array(a, vector, 128);
    random_vector(vector, 128);
    bvconst_set_array(e, vector, 128);
    bvconst_get_mpz(e, 4, z1);

    printf("a  = ");
    bvconst_print(stdout, a, 128);
    printf("\n");
    printf("e  = ");
    bvconst_print(stdout, e, 128);
    printf("\n");
    bvconst_mul(e, 4, a);
    printf("e' = ");
    bvconst_print(stdout, e, 128);
    printf("\n");

    bvconst_get_mpz(a, 4, z0);
    printf("--> conversion a  to mpz: ");
    mpz_out_str(stdout, 10, z0);
    printf("\n");
    printf("--> conversion e  to mpz: ");
    mpz_out_str(stdout, 10, z1);
    printf("\n");
    bvconst_get_mpz(e, 4, z2);
    printf("--> conversion e' to mpz: ");
    mpz_out_str(stdout, 10, z2);
    printf("\n");

    mpz_mul(z0, z0, z1);
    mpz_fdiv_r_2exp(z0, z0, 128);
    printf("--> check:                ");
    mpz_out_str(stdout, 10, z0);
    printf("\n\n");
    assert(mpz_cmp(z0, z2) == 0);
  }

  for (i=0; i<10; i++) {
    printf("test %"PRId32", a := - a\n", i);
    random_vector(vector, 128);
    bvconst_set_array(a, vector, 128);
    bvconst_get_mpz(a, 4, z0);

    printf("a = ");
    bvconst_print(stdout, a, 128);
    printf("\n");
    bvconst_negate(a, 4);
    printf("a = ");
    bvconst_print(stdout, a, 128);
    printf("\n");

    printf("--> conversion  a to mpz: ");
    mpz_out_str(stdout, 10, z0);
    printf("\n");
    bvconst_get_mpz(a, 4, z1);
    printf("--> conversion -a to mpz: ");
    mpz_out_str(stdout, 10, z1);
    printf("\n");

    mpz_neg(z0, z0);
    mpz_fdiv_r_2exp(z0, z0, 128);
    printf("--> check:                ");
    mpz_out_str(stdout, 10, z0);
    printf("\n\n");
    assert(mpz_cmp(z0, z1) == 0);
  }

  for (i=0; i<10; i++) {
    printf("test %"PRId32": e := - a\n", i);
    random_vector(vector, 128);
    bvconst_set_array(a, vector, 128);
    printf("a = ");
    bvconst_print(stdout, a, 128);
    printf("\n");
    bvconst_negate2(e, 4, a);
    printf("e = ");
    bvconst_print(stdout, e, 128);
    printf("\n");

    printf("--> conversion a to mpz: ");
    bvconst_get_mpz(a, 4, z0);
    mpz_out_str(stdout, 10, z0);
    printf("\n");
    bvconst_get_mpz(e, 4, z1);
    printf("--> conversion e to mpz: ");
    mpz_out_str(stdout, 10, z1);
    printf("\n");

    mpz_neg(z0, z0);
    mpz_fdiv_r_2exp(z0, z0, 128);
    printf("--> check:               ");
    mpz_out_str(stdout, 10, z0);
    printf("\n\n");
    assert(mpz_cmp(z0, z1) == 0);
  }

  for (i=0; i<10; i++) {
    printf("test %"PRId32", e = a * b\n", i);
    random_vector(vector, 128);
    bvconst_set_array(a, vector, 128);
    random_vector(vector, 128);
    bvconst_set_array(b, vector, 128);

    printf("a = ");
    bvconst_print(stdout, a, 128);
    printf("\n");
    printf("b = ");
    bvconst_print(stdout, b, 128);
    printf("\n");
    bvconst_mul2(e, 4, a, b);
    printf("e = ");
    bvconst_print(stdout, e, 128);
    printf("\n");

    bvconst_get_mpz(a, 4, z0);
    printf("--> conversion a to mpz: ");
    mpz_out_str(stdout, 10, z0);
    printf("\n");
    bvconst_get_mpz(b, 4, z1);
    printf("--> conversion b to mpz: ");
    mpz_out_str(stdout, 10, z1);
    printf("\n");
    bvconst_get_mpz(e, 4, z2);
    printf("--> conversion e to mpz: ");
    mpz_out_str(stdout, 10, z2);
    printf("\n");

    mpz_mul(z0, z0, z1);
    mpz_fdiv_r_2exp(z0, z0, 128);
    printf("--> check:               ");
    mpz_out_str(stdout, 10, z0);
    printf("\n\n");
    assert(mpz_cmp(z0, z2) == 0);
  }

  for (i=0; i<10; i++) {
    printf("test %"PRId32": e = - (a * b)\n", i);
    random_vector(vector, 128);
    bvconst_set_array(a, vector, 128);
    random_vector(vector, 128);
    bvconst_set_array(b, vector, 128);

    printf("a = ");
    bvconst_print(stdout, a, 128);
    printf("\n");
    printf("b = ");
    bvconst_print(stdout, b, 128);
    printf("\n");
    bvconst_clear(e, 4);
    bvconst_submul(e, 4, a, b);
    printf("e = ");
    bvconst_print(stdout, e, 128);
    printf("\n");

    bvconst_get_mpz(a, 4, z0);
    printf("--> conversion a to mpz: ");
    mpz_out_str(stdout, 10, z0);
    printf("\n");
    bvconst_get_mpz(b, 4, z1);
    printf("--> conversion b to mpz: ");
    mpz_out_str(stdout, 10, z1);
    printf("\n");
    bvconst_get_mpz(d, 4, z2);
    printf("--> conversion d to mpz: ");
    mpz_out_str(stdout, 10, z2);
    printf("\n");
    bvconst_get_mpz(e, 4, z2);
    printf("--> conversion e to mpz: ");
    mpz_out_str(stdout, 10, z2);
    printf("\n");

    mpz_mul(z0, z0, z1);
    mpz_neg(z0, z0);
    mpz_fdiv_r_2exp(z0, z0, 128);
    printf("--> check:               ");
    mpz_out_str(stdout, 10, z0);
    printf("\n\n");
    assert(mpz_cmp(z0, z2) == 0);
  }

  for (i=0; i<10; i++) {
    printf("test %"PRId32": e = a + b\n", i);
    random_vector(vector, 128);
    bvconst_set_array(a, vector, 128);
    random_vector(vector, 128);
    bvconst_set_array(b, vector, 128);

    printf("a = ");
    bvconst_print(stdout, a, 128);
    printf("\n");
    printf("b = ");
    bvconst_print(stdout, b, 128);
    printf("\n");
    bvconst_add2(e, 4, a, b);
    printf("e = ");
    bvconst_print(stdout, e, 128);
    printf("\n");

    bvconst_get_mpz(a, 4, z0);
    printf("--> conversion a to mpz: ");
    mpz_out_str(stdout, 10, z0);
    printf("\n");
    bvconst_get_mpz(b, 4, z1);
    printf("--> conversion b to mpz: ");
    mpz_out_str(stdout, 10, z1);
    printf("\n");
    bvconst_get_mpz(e, 4, z2);
    printf("--> conversion e to mpz: ");
    mpz_out_str(stdout, 10, z2);
    printf("\n");

    mpz_add(z0, z0, z1);
    mpz_fdiv_r_2exp(z0, z0, 128);
    printf("--> check:               ");
    mpz_out_str(stdout, 10, z0);
    printf("\n\n");
    assert(mpz_cmp(z0, z2) == 0);
  }

  for (i=0; i<10; i++) {
    printf("test %"PRId32": e = a - b\n", i);
    random_vector(vector, 128);
    bvconst_set_array(a, vector, 128);
    random_vector(vector, 128);
    bvconst_set_array(b, vector, 128);

    printf("a = ");
    bvconst_print(stdout, a, 128);
    printf("\n");
    printf("b = ");
    bvconst_print(stdout, b, 128);
    printf("\n");
    bvconst_sub2(e, 4, a, b);
    printf("e = ");
    bvconst_print(stdout, e, 128);
    printf("\n");

    bvconst_get_mpz(a, 4, z0);
    printf("--> conversion a to mpz: ");
    mpz_out_str(stdout, 10, z0);
    printf("\n");
    bvconst_get_mpz(b, 4, z1);
    printf("--> conversion b to mpz: ");
    mpz_out_str(stdout, 10, z1);
    printf("\n");
    bvconst_get_mpz(e, 4, z2);
    printf("--> conversion e to mpz: ");
    mpz_out_str(stdout, 10, z2);
    printf("\n");

    mpz_sub(z0, z0, z1);
    mpz_fdiv_r_2exp(z0, z0, 128);
    printf("--> check:               ");
    mpz_out_str(stdout, 10, z0);
    printf("\n\n");
    assert(mpz_cmp(z0, z2) == 0);
  }

  for (i=0; i<10; i++) {
    printf("\ntest %"PRId32": comparisons\n", i);
    random_vector(vector, 25);
    bvconst_set_array(a, vector, 25);
    random_vector(vector, 25);
    bvconst_set_array(b, vector, 25);

    printf("a = ");
    bvconst_print(stdout, a, 25);
    printf("\n");
    printf("b = ");
    bvconst_print(stdout, b, 25);
    printf("\n");

    bvconst_normalize(a, 25);
    bvconst_normalize(b, 25);
    printf("Unsigned tests\n");
    printf(" a le b: %d\n", bvconst_le(a, b, 25));
    printf(" a ge b: %d\n", bvconst_ge(a, b, 25));
    printf(" a lt b: %d\n", bvconst_lt(a, b, 25));
    printf(" a gt b: %d\n", bvconst_gt(a, b, 25));

    printf("Signed tests\n");
    printf(" a sle b: %d\n", bvconst_sle(a, b, 25));
    printf(" a sge b: %d\n", bvconst_sge(a, b, 25));
    printf(" a slt b: %d\n", bvconst_slt(a, b, 25));
    printf(" a sgt b: %d\n", bvconst_sgt(a, b, 25));
  }


  for (i=0; i<10; i++) {
    printf("\ntest %"PRId32": comparisons\n", i);
    random_vector(vector, 32);
    bvconst_set_array(a, vector, 32);
    random_vector(vector, 32);
    bvconst_set_array(b, vector, 32);

    printf("a = ");
    bvconst_print(stdout, a, 32);
    printf("\n");
    printf("b = ");
    bvconst_print(stdout, b, 32);
    printf("\n");

    bvconst_normalize(a, 32);
    bvconst_normalize(b, 32);
    printf("Unsigned tests\n");
    printf(" a le b: %d\n", bvconst_le(a, b, 32));
    printf(" a ge b: %d\n", bvconst_ge(a, b, 32));
    printf(" a lt b: %d\n", bvconst_lt(a, b, 32));
    printf(" a gt b: %d\n", bvconst_gt(a, b, 32));

    printf("Signed tests\n");
    printf(" a sle b: %d\n", bvconst_sle(a, b, 32));
    printf(" a sge b: %d\n", bvconst_sge(a, b, 32));
    printf(" a slt b: %d\n", bvconst_slt(a, b, 32));
    printf(" a sgt b: %d\n", bvconst_sgt(a, b, 32));
  }

  for (i=0; i<10; i++) {
    printf("\ntest %"PRId32": comparisons\n", i);
    random_vector(vector, 33);
    bvconst_set_array(a, vector, 33);
    random_vector(vector, 33);
    bvconst_set_array(b, vector, 33);

    printf("a = ");
    bvconst_print(stdout, a, 33);
    printf("\n");
    printf("b = ");
    bvconst_print(stdout, b, 33);
    printf("\n");

    bvconst_normalize(a, 33);
    bvconst_normalize(b, 33);
    printf("Unsigned tests\n");
    printf(" a le b: %d\n", bvconst_le(a, b, 33));
    printf(" a ge b: %d\n", bvconst_ge(a, b, 33));
    printf(" a lt b: %d\n", bvconst_lt(a, b, 33));
    printf(" a gt b: %d\n", bvconst_gt(a, b, 33));

    printf("Signed tests\n");
    printf(" a sle b: %d\n", bvconst_sle(a, b, 33));
    printf(" a sge b: %d\n", bvconst_sge(a, b, 33));
    printf(" a slt b: %d\n", bvconst_slt(a, b, 33));
    printf(" a sgt b: %d\n", bvconst_sgt(a, b, 33));
  }

  for (i=0; i<10; i++) {
    printf("\ntest %"PRId32": comparisons\n", i);
    random_vector(vector, 63);
    bvconst_set_array(a, vector, 63);
    random_vector(vector, 63);
    bvconst_set_array(b, vector, 63);

    printf("a = ");
    bvconst_print(stdout, a, 63);
    printf("\n");
    printf("b = ");
    bvconst_print(stdout, b, 63);
    printf("\n");

    bvconst_normalize(a, 63);
    bvconst_normalize(b, 63);
    printf("Unsigned tests\n");
    printf(" a le b: %d\n", bvconst_le(a, b, 63));
    printf(" a ge b: %d\n", bvconst_ge(a, b, 63));
    printf(" a lt b: %d\n", bvconst_lt(a, b, 63));
    printf(" a gt b: %d\n", bvconst_gt(a, b, 63));

    printf("Signed tests\n");
    printf(" a sle b: %d\n", bvconst_sle(a, b, 63));
    printf(" a sge b: %d\n", bvconst_sge(a, b, 63));
    printf(" a slt b: %d\n", bvconst_slt(a, b, 63));
    printf(" a sgt b: %d\n", bvconst_sgt(a, b, 63));
  }

  for (i=0; i<10; i++) {
    printf("\ntest %"PRId32": comparisons\n", i);
    random_vector(vector, 64);
    bvconst_set_array(a, vector, 64);
    random_vector(vector, 64);
    bvconst_set_array(b, vector, 64);

    printf("a = ");
    bvconst_print(stdout, a, 64);
    printf("\n");
    printf("b = ");
    bvconst_print(stdout, b, 64);
    printf("\n");

    bvconst_normalize(a, 64);
    bvconst_normalize(b, 64);
    printf("Unsigned tests\n");
    printf(" a le b: %d\n", bvconst_le(a, b, 64));
    printf(" a ge b: %d\n", bvconst_ge(a, b, 64));
    printf(" a lt b: %d\n", bvconst_lt(a, b, 64));
    printf(" a gt b: %d\n", bvconst_gt(a, b, 64));

    printf("Signed tests\n");
    printf(" a sle b: %d\n", bvconst_sle(a, b, 64));
    printf(" a sge b: %d\n", bvconst_sge(a, b, 64));
    printf(" a slt b: %d\n", bvconst_slt(a, b, 64));
    printf(" a sgt b: %d\n", bvconst_sgt(a, b, 64));
  }

  printf("\nMore comparisons\n");
  random_vector(vector, 64);
  bvconst_set_array(a, vector, 64);
  bvconst_set_array(b, vector, 64);
  printf("a = ");
  bvconst_print(stdout, a, 64);
  printf("\n");
  printf("b = ");
  bvconst_print(stdout, b, 64);
  printf("\n");

  bvconst_normalize(a, 64);
  bvconst_normalize(b, 64);
  printf("Unsigned tests\n");
  printf(" a le b: %d\n", bvconst_le(a, b, 64));
  printf(" a ge b: %d\n", bvconst_ge(a, b, 64));
  printf(" a lt b: %d\n", bvconst_lt(a, b, 64));
  printf(" a gt b: %d\n", bvconst_gt(a, b, 64));

  printf("Signed tests\n");
  printf(" a sle b: %d\n", bvconst_sle(a, b, 64));
  printf(" a sge b: %d\n", bvconst_sge(a, b, 64));
  printf(" a slt b: %d\n", bvconst_slt(a, b, 64));
  printf(" a sgt b: %d\n", bvconst_sgt(a, b, 64));


  random_vector(vector, 65);
  bvconst_set_array(a, vector, 65);
  bvconst_set_array(b, vector, 65);
  printf("a = ");
  bvconst_print(stdout, a, 65);
  printf("\n");
  printf("b = ");
  bvconst_print(stdout, b, 65);
  printf("\n");

  bvconst_normalize(a, 65);
  bvconst_normalize(b, 65);
  printf("Unsigned tests\n");
  printf(" a le b: %d\n", bvconst_le(a, b, 65));
  printf(" a ge b: %d\n", bvconst_ge(a, b, 65));
  printf(" a lt b: %d\n", bvconst_lt(a, b, 65));
  printf(" a gt b: %d\n", bvconst_gt(a, b, 65));

  printf("Signed tests\n");
  printf(" a sle b: %d\n", bvconst_sle(a, b, 65));
  printf(" a sge b: %d\n", bvconst_sge(a, b, 65));
  printf(" a slt b: %d\n", bvconst_slt(a, b, 65));
  printf(" a sgt b: %d\n", bvconst_sgt(a, b, 65));

  random_vector(vector, 63);
  bvconst_set_array(a, vector, 63);
  bvconst_set_array(b, vector, 63);
  printf("a = ");
  bvconst_print(stdout, a, 63);
  printf("\n");
  printf("b = ");
  bvconst_print(stdout, b, 63);
  printf("\n");

  bvconst_normalize(a, 63);
  bvconst_normalize(b, 63);
  printf("Unsigned tests\n");
  printf(" a le b: %d\n", bvconst_le(a, b, 63));
  printf(" a ge b: %d\n", bvconst_ge(a, b, 63));
  printf(" a lt b: %d\n", bvconst_lt(a, b, 63));
  printf(" a gt b: %d\n", bvconst_gt(a, b, 63));

  printf("Signed tests\n");
  printf(" a sle b: %d\n", bvconst_sle(a, b, 63));
  printf(" a sge b: %d\n", bvconst_sge(a, b, 63));
  printf(" a slt b: %d\n", bvconst_slt(a, b, 63));
  printf(" a sgt b: %d\n", bvconst_sgt(a, b, 63));

  printf("\nTest powers of two\n");
  mpz_set_ui(z0, 1);
  for (i=0; i<128; i++) {
    printf("z0 = ");
    mpz_out_str(stdout, 10, z0);
    printf("\n");
    bvconst_set_mpz(a, 4, z0);
    printf("a = ");
    bvconst_print(stdout, a, 128);
    printf("\n");

    n = bvconst_is_power_of_two(a, 4);
    if (n < 0) {
      printf("--> not a power of 2\n\n");
    } else {
      printf("--> a = 2^%"PRId32"\n\n", n);
    }
    mpz_add(z0, z0, z0);
  }


  a[0] = 0;
  a[1] = 1024;
  a[2] = 0;
  a[3] = 36136287;
  printf("a = ");
  bvconst_print(stdout, a, 128);
  printf("\n");
  n = bvconst_is_power_of_two(a, 4);
  if (n < 0) {
    printf("--> not a power of 2\n\n");
  } else {
    printf("--> a = 2^%"PRId32"\n\n", n);
  }

  a[0] = 0;
  a[1] = 1024;
  a[2] = 31209;
  a[3] = 0;
  printf("a = ");
  bvconst_print(stdout, a, 128);
  printf("\n");
  n = bvconst_is_power_of_two(a, 4);
  if (n < 0) {
    printf("--> not a power of 2\n\n");
  } else {
    printf("--> a = 2^%"PRId32"\n\n", n);
  }


  a[0] = 0;
  a[1] = 1024;
  a[2] = 0;
  a[3] = 0;
  printf("a = ");
  bvconst_print(stdout, a, 128);
  printf("\n");
  n = bvconst_is_power_of_two(a, 4);
  if (n < 0) {
    printf("--> not a power of 2\n\n");
  } else {
    printf("--> a = 2^%"PRId32"\n\n", n);
  }


  a[0] = 128;
  a[1] = 1024;
  a[2] = 0;
  a[3] = 0;
  printf("a = ");
  bvconst_print(stdout, a, 128);
  printf("\n");
  n = bvconst_is_power_of_two(a, 4);
  if (n < 0) {
    printf("--> not a power of 2\n\n");
  } else {
    printf("--> a = 2^%"PRId32"\n\n", n);
  }




  bvconst_clear(a, 4);
  for (i=0; i<256; i++) {
    printf("a = ");
    bvconst_print(stdout, a, 128);
    printf("\n");

    n = bvconst_is_power_of_two(a, 4);
    if (n < 0) {
      printf("--> not a power of 2\n\n");
    } else {
      printf("--> a = 2^%"PRId32"\n\n", n);
    }
    bvconst_add_one(a, 4);
  }

  for (i=0; i<10; i++) {
    printf("test %"PRId32": power of two\n", i);
    random_vector(vector, 128);
    bvconst_set_array(a, vector, 128);

    for (j=0; j<64; j++) {
      printf("a = ");
      bvconst_print(stdout, a, 128);
      printf("\n");
      n = bvconst_is_power_of_two(a, 4);
      if (n < 0) {
	printf("--> not a power of 2\n\n");
      } else {
	printf("--> a = 2^%"PRId32"\n\n", n);
      }
      bvconst_clr_bit(a, j);
      bvconst_clr_bit(a, 127 - j);
    }
  }


  // test mulpower
  for (i=0; i<130; i++) {
    bvconst_set_one(a, 4);    // a = 1
    bvconst_set32(b, 4, 2);   // b = 2
    // compute a * b^i = 2^i
    bvconst_mulpower(a, 4, b, i);
    printf("---> mulpower: a = b^%"PRIu32" = 2^%"PRIu32"\n", i, i);
    printf("     b = ");
    bvconst_print(stdout, b, 128);
    printf("\n");
    printf("     a = ");
    bvconst_print(stdout, a, 128);
    printf("\n");
  }

  // test mulpower
  for (i=0; i<40; i++) {
    bvconst_set32(a, 4, 4);       // a = 0b0..00100
    bvconst_set_minus_one(b, 4);  // b = 0b11..1111
    // compute a * b^i = -4 or +4
    bvconst_mulpower(a, 4, b, i);
    printf("---> mulpower: a = 4 * b^%"PRIu32" = 4 * (-1)^%"PRIu32"\n", i, i);
    printf("     b = ");
    bvconst_print(stdout, b, 128);
    printf("\n");
    printf("     a = ");
    bvconst_print(stdout, a, 128);
    printf("\n");
  }

  // test mulpower
  for (i=0; i<40; i++) {
    bvconst_set32(a, 4, 4);     // a = 0b0..00100
    bvconst_clear(b, 4);        // b = 0
    // compute a * b^i = 0
    bvconst_mulpower(a, 4, b, i);
    printf("---> mulpower: a = 4 * b^%"PRIu32"\n", i);
    printf("     b = ");
    bvconst_print(stdout, b, 128);
    printf("\n");
    printf("     a = ");
    bvconst_print(stdout, a, 128);
    printf("\n");
  }


  // test is_one and is_minus_one
  printf("\n\n");
  for (i=1; i<=128; i++) {
    bvconst_set_one(a, 4);         // a = 1
    bvconst_set_minus_one(b, 4);   // b = -1
    bvconst_clear(c, 4);           // c = 0
    random_vector(vector, i);
    bvconst_set_array(d, vector, i); // d = random

    // make all i-bit length constant
    bvconst_normalize(a, i);
    bvconst_normalize(b, i);
    bvconst_normalize(c, i);
    bvconst_normalize(d, i);

    n = (i+31) >> 5;  // number of words
    printf("---> %"PRIu32" bits\n", i);
    printf("a = ");
    bvconst_print(stdout, a, i);
    printf(": is_one = %s, is_minus_one = %s\n", b2str(bvconst_is_one(a, n)), b2str(bvconst_is_minus_one(a, i)));

    printf("b = ");
    bvconst_print(stdout, b, i);
    printf(": is_one = %s, is_minus_one = %s\n", b2str(bvconst_is_one(b, n)), b2str(bvconst_is_minus_one(b, i)));

    printf("c = ");
    bvconst_print(stdout, c, i);
    printf(": is_one = %s, is_minus_one = %s\n", b2str(bvconst_is_one(c, n)), b2str(bvconst_is_minus_one(c, i)));

    printf("d = ");
    bvconst_print(stdout, d, i);
    printf(": is_one = %s, is_minus_one = %s\n", b2str(bvconst_is_one(d, n)), b2str(bvconst_is_minus_one(d, i)));

    printf("\n");
    fflush(stdout);
  }

  // test is_min_signed and is_max_signed
  printf("\n\n");
  for (i=1; i<=128; i++) {
    bvconst_clear(a, 4);           // a = 0
    bvconst_set_minus_one(b, 4);   // b = -1
    bvconst_clear(c, 4);
    bvconst_set_bit(c, i-1);       // c = 0b10000000 (smallest negative integer)
    bvconst_set_minus_one(d, 4);
    bvconst_clr_bit(d, i-1);       // d = 0b01111111 (largest positive integer)
    random_vector(vector, i);
    bvconst_set_array(e, vector, i); // e = random

    // make all i-bit length constant
    bvconst_normalize(a, i);
    bvconst_normalize(b, i);
    bvconst_normalize(c, i);
    bvconst_normalize(d, i);
    bvconst_normalize(e, i);

    printf("---> %"PRIu32" bits\n", i);
    printf("a = ");
    bvconst_print(stdout, a, i);
    printf(": is_min_signed = %s, is_max_signed = %s\n", b2str(bvconst_is_min_signed(a, i)), b2str(bvconst_is_max_signed(a, i)));

    printf("b = ");
    bvconst_print(stdout, b, i);
    printf(": is_min_signed = %s, is_max_signed = %s\n", b2str(bvconst_is_min_signed(b, i)), b2str(bvconst_is_max_signed(b, i)));

    printf("c = ");
    bvconst_print(stdout, c, i);
    printf(": is_min_signed = %s, is_max_signed = %s\n", b2str(bvconst_is_min_signed(c, i)), b2str(bvconst_is_max_signed(c, i)));

    printf("d = ");
    bvconst_print(stdout, d, i);
    printf(": is_min_signed = %s, is_max_signed = %s\n", b2str(bvconst_is_min_signed(d, i)), b2str(bvconst_is_max_signed(d, i)));

    printf("e = ");
    bvconst_print(stdout, e, i);
    printf(": is_min_signed = %s, is_max_signed = %s\n", b2str(bvconst_is_min_signed(e, i)), b2str(bvconst_is_max_signed(e, i)));

    printf("\n");
    fflush(stdout);
  }

  for (i=100; i<256; i += 10) {
    for (j=1; j<=i; j += 9) {
      test_set_extend(i, j);
    }
  }

  mpz_clear(z0);
  mpz_clear(z1);
  mpz_clear(z2);


  free_constants();

  return 0;
}