コード例 #1
0
ファイル: motor.c プロジェクト: elleveldy/byggern
uint16_t motor_encoder_read(){

	uint8_t msb;
	uint8_t lsb;
	
	
	//enable output
	motor_encoder_output_enable(1);
	
	//read MSB to data
	motor_encoder_select_byte(0);
	_delay_us(20);
	msb = reverse_bits(motor_encoder_byte_read());
	
	//read LSB to data
	motor_encoder_select_byte(1);
	_delay_us(20);
	lsb = reverse_bits(motor_encoder_byte_read());
	
	//disable output
	motor_encoder_output_enable(0);
	
	
	uint16_t data = (msb << 8) + lsb;
	
	return data;

	
}
コード例 #2
0
ファイル: reverse_bits.c プロジェクト: mcuer/test
int		main(void)
{	
	print_bits(130);
	ft_putchar('\n');
	reverse_bits(130);
	return (0);
}
コード例 #3
0
int
main(void)
{
	printf("%u\n", reverse_bits(25));

	return EXIT_SUCCESS;
}
コード例 #4
0
int main(int argc, char *argv[]) {
  // check for the right number of arguments
  if (argc != 4) {
    printf("Error: Usage: ./cp1-problem2 [int1] [int2] [int3]\n");
    return 0;
  }

  // interpret the variables
  int int1 = atoi(argv[1]);
  int int2 = atoi(argv[2]);
  int int3 = atoi(argv[3]);
  
  // calculate the result for the first problem
  int result1 = most_ones(int1, int2, int3);  
  printf("Success: The argument with the most 1s is: %d\n", result1);

  // calculate the result for the second problem
  int result2 = xor_all(int1, int2, int3);  
  printf("Success: The XOR of all three ints is: %d\n", result2);

  // calculate the result for the third problem
  int result3 = reverse_bits(int1);  
  printf("Success: The reversal of the bits of %d is: %d\n", int1, result3);
 
  return 0;
}
コード例 #5
0
bool Fft_transformRadix2(double real[], double imag[], size_t n) {
	// Length variables
	bool status = false;
	int levels = 0;  // Compute levels = floor(log2(n))
	for (size_t temp = n; temp > 1U; temp >>= 1)
		levels++;
	if ((size_t)1U << levels != n)
		return false;  // n is not a power of 2
	
	// Trignometric tables
	if (SIZE_MAX / sizeof(double) < n / 2)
		return false;
	size_t size = (n / 2) * sizeof(double);
	double *cos_table = malloc(size);
	double *sin_table = malloc(size);
	if (cos_table == NULL || sin_table == NULL)
		goto cleanup;
	for (size_t i = 0; i < n / 2; i++) {
		cos_table[i] = cos(2 * M_PI * i / n);
		sin_table[i] = sin(2 * M_PI * i / n);
	}
	
	// Bit-reversed addressing permutation
	for (size_t i = 0; i < n; i++) {
		size_t j = reverse_bits(i, levels);
		if (j > i) {
			double temp = real[i];
			real[i] = real[j];
			real[j] = temp;
			temp = imag[i];
			imag[i] = imag[j];
			imag[j] = temp;
		}
	}
	
	// Cooley-Tukey decimation-in-time radix-2 FFT
	for (size_t size = 2; size <= n; size *= 2) {
		size_t halfsize = size / 2;
		size_t tablestep = n / size;
		for (size_t i = 0; i < n; i += size) {
			for (size_t j = i, k = 0; j < i + halfsize; j++, k += tablestep) {
				size_t l = j + halfsize;
				double tpre =  real[l] * cos_table[k] + imag[l] * sin_table[k];
				double tpim = -real[l] * sin_table[k] + imag[l] * cos_table[k];
				real[l] = real[j] - tpre;
				imag[l] = imag[j] - tpim;
				real[j] += tpre;
				imag[j] += tpim;
			}
		}
		if (size == n)  // Prevent overflow in 'size *= 2'
			break;
	}
	status = true;
	
cleanup:
	free(cos_table);
	free(sin_table);
	return status;
}
コード例 #6
0
int main(void) {
    unsigned int result = reverse_bits(25);

    printf("%ld\n", result);

    return 0;
}
コード例 #7
0
ファイル: search.c プロジェクト: LeoNelson/hypermail
static int addb(const char *token, struct body *bp)
{
    struct search_text **pp = &text_tree;
    struct search_text *p = *pp;
    int r;
#ifndef BY_TOKEN_STRING
    int token_length = strlen(token);
    unsigned int token_crc32 = crc32_lower((const unsigned char *)token, token_length);
#endif
    static struct search_text *next_token = NULL;
    if (!text_tree) {
	next_token = (struct search_text *)malloc(max_tokens * sizeof(struct search_text));
	if (!next_token) {
	    snprintf(errmsg, sizeof(errmsg), "Couldn't allocate %d bytes of memory.", max_tokens * sizeof(struct search_text));
	    progerr(errmsg);
	}
	memset(next_token, 0, max_tokens * sizeof(struct search_text));
    }
    ++b_times_entered;
    while (1) {
	++b_loops_done;
	p = *pp;
	if (!p) {
	    *pp = p = next_token++;
	    if (next_token >= text_tree + max_tokens) {
		snprintf(errmsg, sizeof(errmsg), "Too many distinct tokens(%d)", max_tokens);
		progerr(errmsg);
	    }
	    p->left = p->right = NULL;
#ifdef BY_TOKEN_STRING
	    strncpy(p->token, token, MAXSEARCHTOKEN);
	    p->token[MAXSEARCHTOKEN - 1] = 0;
#else
	    p->token_length = token_length;
	    p->token_crc32 = token_crc32;
#endif				/* !BY_TOKEN_STRING */
	    p->itok = reverse_bits(next_itoken++);
#ifdef COUNT_TOKEN_FREQ
	    p->count = 1;
#endif
	    if (!next_itoken >= max_tokens) {
		snprintf(errmsg, sizeof(errmsg), "Internal error - too many distinct tokens.");
		progerr(errmsg);
	    }
	    return p->itok;
	}
	r = COMPARE_TOKEN(token, p);
	if (!r) {
#ifdef COUNT_TOKEN_FREQ
	    ++p->count;
#endif
	    return p->itok;
	}
	if (r < 0)
	    pp = &p->left;
	else
	    pp = &p->right;
    }
}
コード例 #8
0
ファイル: doctors.c プロジェクト: sprunka/doctors
// Horizontally flips the indicated GBitmap in-place.  Requires
// that the width be a multiple of 8 pixels.
void flip_bitmap_x(GBitmap *image) {
  int height = image->bounds.size.h;
  int width = image->bounds.size.w;  // multiple of 8, by our convention.
  int width_bytes = width / 8;
  int stride = image->row_size_bytes; // multiple of 4, by Pebble.
  uint8_t *data = image->addr;

  for (int y = 0; y < height; ++y) {
    uint8_t *row = data + y * stride;
    for (int x1 = (width_bytes - 1) / 2; x1 >= 0; --x1) {
      int x2 = width_bytes - 1 - x1;
      uint8_t b = reverse_bits(row[x1]);
      row[x1] = reverse_bits(row[x2]);
      row[x2] = b;
    }
  }
}
コード例 #9
0
ファイル: mode-gcm.c プロジェクト: patrick-ken/kernel_808l
void ssh_gf2n_128_init_ui(SshUInt32 *e, unsigned char w)
{
  w = reverse_bits(w);
  
  e[0] = (w & 0xff) << 24;
  e[1] = 0;
  e[2] = 0;
  e[3] = 0;
}
コード例 #10
0
ファイル: big_integer.cpp プロジェクト: slelaron/big_integer
void big_integer::make_binary_convenient()
{
	number.push_back(0);
	if (sign == NEGATIVE)
	{
		reverse_bits();
		++(*this);
	}
}
コード例 #11
0
// Public library function. Returns NULL if successful, a string starting with "I/O error: "
// if an I/O error occurred (please see perror()), or a string if some other error occurred.
const char *modify_file_crc32(const char *path, uint64_t offset, uint32_t newcrc, bool printstatus) {
	FILE *f = fopen(path, "r+b");
	if (f == NULL)
		return "I/O error: fopen";
	
	// Read entire file and calculate original CRC-32 value.
	// Note: We can't use fseek(f, 0, SEEK_END) + ftell(f) to determine the length of the file, due to undefined behavior.
	// To be portable, we also avoid using POSIX fseeko()+ftello() or Windows GetFileSizeEx()/_filelength().
	uint64_t length;
	uint32_t crc = get_crc32_and_length(f, &length);
	if (offset > UINT64_MAX - 4 || offset + 4 > length) {
		fclose(f);
		return "Error: Byte offset plus 4 exceeds file length";
	}
	if (printstatus)
		fprintf(stdout, "Original CRC-32: %08" PRIX32 "\n", reverse_bits(crc));
	
	// Compute the change to make
	uint32_t delta = crc ^ newcrc;
	delta = (uint32_t)multiply_mod(reciprocal_mod(pow_mod(2, (length - offset) * 8)), delta);
	
	// Patch 4 bytes in the file
	fseek64(f, offset);
	for (int i = 0; i < 4; i++) {
		int b = fgetc(f);
		if (b == EOF) {
			fclose(f);
			return "I/O error: fgetc";
		}
		b ^= (int)((reverse_bits(delta) >> (i * 8)) & 0xFF);
		if (fseek(f, -1, SEEK_CUR) != 0) {
			fclose(f);
			return "I/O error: fseek";
		}
		if (fputc(b, f) == EOF) {
			fclose(f);
			return "I/O error: fputc";
		}
		if (fflush(f) == EOF) {
			fclose(f);
			return "I/O error: fflush";
		}
	}
	if (printstatus)
		fprintf(stdout, "Computed and wrote patch\n");
	
	// Recheck entire file
	bool match = get_crc32_and_length(f, &length) == newcrc;
	fclose(f);
	if (match) {
		if (printstatus)
			fprintf(stdout, "New CRC-32 successfully verified\n");
		return NULL;  // Success
	} else
		return "Assertion error: Failed to update CRC-32 to desired value";
}
コード例 #12
0
ファイル: wright.c プロジェクト: R1chChapp3rs/rosewright
// Horizontally flips the indicated BmpContainer in-place.  Requires
// that the width be a multiple of 8 pixels.
void flip_bitmap_x(BmpContainer *image, int *cx) {
  int height = image->bmp.bounds.size.h;
  int width = image->bmp.bounds.size.w;  // multiple of 8, by our convention.
  int width_bytes = width / 8;
  int stride = image->bmp.row_size_bytes; // multiple of 4, by Pebble.
  uint8_t *data = image->bmp.addr;

  for (int y = 0; y < height; ++y) {
    uint8_t *row = data + y * stride;
    for (int x1 = (width_bytes - 1) / 2; x1 >= 0; --x1) {
      int x2 = width_bytes - 1 - x1;
      uint8_t b = reverse_bits(row[x1]);
      row[x1] = reverse_bits(row[x2]);
      row[x2] = b;
    }
  }

  if (cx != NULL) {
    *cx = width- 1 - *cx;
  }
}
コード例 #13
0
ファイル: gf_convert.c プロジェクト: BrianGladman/modes
void convert_representation(gf_t dest, const gf_t source, transform rev)
{
    if(rev & REVERSE_BITS)
    {
        reverse_bits(dest, source);
        if(rev & REVERSE_BYTES)
            bswap128_block(dest, dest);
    }
    else if(rev & REVERSE_BYTES)
        bswap128_block(dest, source);
    else if(dest != source)
        memcpy(dest, source, GF_BYTE_LEN);
}
コード例 #14
0
ファイル: main.c プロジェクト: amstan/rpi-spi-uart
// Writes an number of bytes to SPI
void spi_uart_tx(char c) {
	volatile uint32_t* paddr = bcm2835_spi0 + BCM2835_SPI0_CS/4;
	volatile uint32_t* fifo = bcm2835_spi0 + BCM2835_SPI0_FIFO/4;
	
	bcm2835_gpio_fsel(RPI_GPIO_P1_19, BCM2835_GPIO_FSEL_ALT0);
	
	//BUG: The start bit is always 1.5 periods long, probably unfixable
	
	// This is Polled transfer as per section 10.6.1
	// BUG ALERT: what happens if we get interupted in this section, and someone else
	// accesses a different peripheral?
	
	// Clear TX and RX fifos
	bcm2835_peri_set_bits(paddr, BCM2835_SPI0_CS_CLEAR, BCM2835_SPI0_CS_CLEAR);
	
	// Set TA = 1
	bcm2835_peri_set_bits(paddr, BCM2835_SPI0_CS_TA, BCM2835_SPI0_CS_TA);
	
		// Maybe wait for TXD
		while (!(bcm2835_peri_read(paddr) & BCM2835_SPI0_CS_TXD))
			;
		
		// Write to FIFO, no barrier
		bcm2835_peri_write_nb(fifo, reverse_bits(c));
		
		// Read from FIFO to prevent stalling
		while (bcm2835_peri_read(paddr) & BCM2835_SPI0_CS_RXD)
			(void) bcm2835_peri_read_nb(fifo);
// 		bcm2835_gpio_fsel(RPI_GPIO_P1_19, BCM2835_GPIO_FSEL_ALT0);
	
	// Wait for DONE to be set
	while (!(bcm2835_peri_read_nb(paddr) & BCM2835_SPI0_CS_DONE)) {
// 		while (bcm2835_peri_read(paddr) & BCM2835_SPI0_CS_RXD)
// 			(void) bcm2835_peri_read_nb(fifo);
	}
	
// 	bcm2835_delayMicroseconds(10);
	
	// Set TA = 0, and also set the barrier
	bcm2835_peri_set_bits(paddr, 0, BCM2835_SPI0_CS_TA);
	
	//TODO: THe program might be interrupted in here, corrupting the character.
	
	bcm2835_gpio_fsel(RPI_GPIO_P1_19, BCM2835_GPIO_FSEL_OUTP); // MOSI
	bcm2835_gpio_set(RPI_GPIO_P1_19); //idle high
	bcm2835_gpio_set_pud(RPI_GPIO_P1_19,BCM2835_GPIO_PUD_UP);
	bcm2835_delayMicroseconds(40);
}
コード例 #15
0
// Returns a pointer to an opaque structure of FFT tables. n must be a power of 2 and n >= 4.
void *fft_init(size_t n) {
	// Check size argument
	if (n < 4 || n > UINT64_MAX || (n & (n - 1)) != 0)
		return NULL;  // Error: Size is too small or is not a power of 2
	if (n - 4 > SIZE_MAX / sizeof(double) / 2 || n > SIZE_MAX / sizeof(size_t))
		return NULL;  // Error: Size is too large, which makes memory allocation impossible
	
	// Allocate structure
	struct FftTables *tables = malloc(sizeof(struct FftTables));
	if (tables == NULL)
		return NULL;
	tables->n = n;
	
	// Allocate arrays
	tables->bit_reversed = malloc(n * sizeof(size_t));
	tables->trig_tables = malloc((n - 4) * 2 * sizeof(double));
	if (tables->bit_reversed == NULL || tables->trig_tables == NULL) {
		free(tables->bit_reversed);
		free(tables->trig_tables);
		free(tables);
		return NULL;
	}
	
	// Precompute bit reversal table
	int levels = floor_log2(n);
	uint64_t i;
	for (i = 0; i < n; i++)
		tables->bit_reversed[i] = reverse_bits(i, levels);
	
	// Precompute the packed trigonometric table for each FFT internal level
	uint64_t size;
	uint64_t k = 0;
	for (size = 8; size <= n; size *= 2) {
		for (i = 0; i < size / 2; i += 4) {
			uint64_t j;
			for (j = 0; j < 4; j++, k++)
				tables->trig_tables[k] = accurate_sine(i + j + size / 4, size);  // Cosine
			for (j = 0; j < 4; j++, k++)
				tables->trig_tables[k] = accurate_sine(i + j, size);  // Sine
		}
		if (size == n)
			break;
	}
	return tables;
}
コード例 #16
0
ファイル: huffman.c プロジェクト: lxwgcool/Huffman_Coding
/*
 * new_code builds a huffman_code from a leaf in
 * a Huffman tree.
 */
static huffman_code*
new_code(const huffman_node* leaf)
{
    /* Build the huffman code by walking up to
     * the root node and then reversing the bits,
     * since the Huffman code is calculated by
     * walking down the tree. */
    unsigned long numbits = 0;
    unsigned char* bits = NULL;
    huffman_code *p;

    while(leaf && leaf->parent)
    {
        huffman_node *parent = leaf->parent;
        unsigned char cur_bit = (unsigned char)(numbits % 8);
        unsigned long cur_byte = numbits / 8;

        /* If we need another byte to hold the code,
           then allocate it. */
        if(cur_bit == 0)
        {
            size_t newSize = cur_byte + 1;
            bits = (unsigned char*)realloc(bits, newSize);
            bits[newSize - 1] = 0; /* Initialize the new byte. */
        }

        /* If a one must be added then or it in. If a zero
         * must be added then do nothing, since the byte
         * was initialized to zero. */
        if(leaf == parent->one)
            bits[cur_byte] |= 1 << cur_bit;

        ++numbits;
        leaf = parent;
    }

    if(bits)
        reverse_bits(bits, numbits);

    p = (huffman_code*)malloc(sizeof(huffman_code));
    p->numbits = numbits;
    p->bits = bits;
    return p;
}
コード例 #17
0
ファイル: HuffmanCode.cpp プロジェクト: sfgorky/huffman
///////////////////////////////////////////////////////////////////////////////
// new_code builds a HuffmanCode from a leaf in a Huffman tree.
HuffmanCode::HuffmanCode(const HuffmanNode* leaf)
    :   m_nbBits(0)
    ,   m_bits(0)
    ,   m_leaf(leaf)
{
    // Build the huffman code by walking up to the root node and then
    // reversing the bits, since the Huffman code is calculated by
    // walking down the tree.
    unsigned long numbits = 0;
    unsigned char* bits   = nullptr;

    while(leaf && leaf->parent())
    {
        HuffmanNode* parent = leaf->parent();
        unsigned char cur_bit  = (unsigned char)(numbits % 8);
        unsigned long cur_byte = numbits / 8;

        // If we need another byte to hold the code, then allocate it
        if(cur_bit == 0)
        {
            size_t newSize = cur_byte + 1;
            bits = (Byte*)realloc(bits, newSize);
            bits[newSize-1] = 0; // Initialize the new byte.
        }

        //If a one must be added then or it in. If a zeromust be added then do nothing,
        // since the byte was initialized to zero.
        if(leaf == parent->one())
        {
            bits[cur_byte] |= 1 << cur_bit;
        }
        ++numbits;
        leaf = parent;
    }
    if(bits)
    {
        reverse_bits(bits, numbits);
    }
    delete m_bits;

    m_nbBits = numbits;
    m_bits   = bits;
}
コード例 #18
0
ファイル: mode-gcm.c プロジェクト: patrick-ken/kernel_808l
void
ssh_gf2n_128_table_byte_init(void *workspace, SshUInt32 *H, 
			     SshUInt32 moduli, unsigned int table_index)
{
  SshUInt32 *m = workspace;
  unsigned int i, j, index;

  SSH_ASSERT(table_index < 16);

  /* m[i] = x_i . H . P^8i */
  for (i = 0; i < 256; i++)
    {
      index = reverse_bits((unsigned char)i);
      ssh_gf2n_128_init_ui(m + 4 * index, (unsigned char)i);
      
      ssh_gf2n_128_mul(m + 4 * index, H, moduli);
      for (j = 0; j < 8 * table_index; j++)
	ssh_gf2n_128_mul_base(m + 4 * index, moduli);
    }
}
コード例 #19
0
ファイル: fft.cpp プロジェクト: digitalinteraction/expressy
static void fft()
{
	for (int i = 0; i < length; i++)
	{
		int j = reverse_bits(i, numBits);
		real[j] = samples[i];
		imag[j] = 0.0f;
	}

	int x = 0;
	for (int i = 0; i < numBits; i++)  // Cooley-Tukey 
	{
		int m = 1 << i;
		int n = m << 1;

		for (int k = 0; k < m; k++)
		{
			float c = cosTable[x];
			float s = sinTable[x];
			x++;

			float tr, ti;
			for (int j = k; j < length; j += n)
			{
				tr = c * real[j + m] - s * imag[j + m];
				ti = s * real[j + m] + c * imag[j + m];

				real[j + m] = real[j] - tr;
				imag[j + m] = imag[j] - ti;

				real[j] += tr;
				imag[j] += ti;
			}
		}
	}
	
	for (int i = 0; i < length; i++)  // power spectrum
	{
		samples[i] = real[i]*real[i] + imag[i]*imag[i];
	}
}
コード例 #20
0
int main(int argc, char *argv[]) {
	// Handle arguments
	if (argc != 4) {
		fprintf(stderr, "Usage: %s FileName ByteOffset NewCrc32Value\n", argv[0]);
		return EXIT_FAILURE;
	}
	
	// Parse and check file offset argument
	uint64_t offset;
	if (sscanf(argv[2], "%" SCNu64, &offset) != 1) {
		fprintf(stderr, "Error: Invalid byte offset\n");
		return EXIT_FAILURE;
	}
	char temp[21] = {0};
	sprintf(temp, "%" PRIu64, offset);
	if (strcmp(temp, argv[2]) != 0) {
		fprintf(stderr, "Error: Invalid byte offset\n");
		return EXIT_FAILURE;
	}
	
	// Parse and check new CRC argument
	uint32_t newcrc;
	if (strlen(argv[3]) != 8 || argv[3][0] == '+' || argv[3][0] == '-'
			|| sscanf(argv[3], "%" SCNx32, &newcrc) != 1) {
		fprintf(stderr, "Error: Invalid new CRC-32 value\n");
		return EXIT_FAILURE;
	}
	newcrc = reverse_bits(newcrc);
	
	// Process the file
	const char *errmsg = modify_file_crc32(argv[1], offset, newcrc, true);
	if (errmsg == NULL)
		return EXIT_SUCCESS;
	else if (0 < strcmp(errmsg, "I/O error: ") && strcmp(errmsg, "I/O error:!") < 0)  // Prefix test
		perror(errmsg);
	else
		fprintf(stderr, "%s\n", errmsg);
	return EXIT_FAILURE;
}
コード例 #21
0
ファイル: main.cpp プロジェクト: CCJY/coliru
bool is_binary_palindrome( unsigned int n ) { return n == reverse_bits(n) ; }
コード例 #22
0
int _select_beam(unsigned int base,struct ControlPRM *client){

        /* This code selects the beam code to use.  
        */
        
        int code, beamnm, temp, oldB, oldC,hi,lo;
        double freq_mhz,angle;

        unsigned int portA,portB,portC,cntl;        
        if (verbose > 1) { 
          printf("DIO: Select beam\n",client->tfreq);	
          printf("  Base Beamnm: %d\n",client->tbeam);	
          printf("  Selected Freq [kHz]: %d\n",client->tfreq);	
          printf("  Selected Radar: %d\n",client->radar);	
          printf("  Selected Beam angle: %f\n",client->tbeamazm);	
          printf("  Selected Beam width: %f\n",client->tbeamwidth);	
        }  
        /* the beam number is 4 bits.  This number
           uses (lo) bits 5-6 of CH0, PortB , and (hi) bits 6-7 of CH0, PortC
           to output the beam number. Note: The beam number is used in addressing
           the old style phasing matrix.
        */
        beamnm=client->tbeam;
        if ( (beamnm>MAX_BEAM) || (beamnm<0) ){
                fprintf(stderr,"INVALID BEAMNM - must be between 0 and %d\n",MAX_BEAM);
                beamnm=0;
                lo=0;
 		hi=0;
        } else {
        	lo=beamnm & 0x3;
        	hi=beamnm & 0xC;
		hi=hi >> 2;
        }

        freq_mhz=client->tfreq*1E3;
        /* the beam code is 13 bits, pAD0 thru pAD12.  This code
           uses bits 0-7 of CH0, PortA, and bits 0-4 of CH0, PortB
           to output the beam code. Note: The beam code is an address
           of the EEPROMs in the phasing cards.  This code is broadcast
           to ALL phasing cards.  If you are witing the EEPROM, then this
           be the beam code you are writing
        */
        /* Lookup beamcode using phasing card lookup table */
	/* 
         * MSI phasing cards programmed with 
         * frequency optimal attenuatin values
         * in different bands.
         */ 
        code=lookup_beamcode_by_freq(client->radar-1,freq_mhz,beamnm);

        if (verbose > 1) 
          printf("  Selected Beamcode: %d\n",code);	

        if (verbose > 1) printf("Reversing Code: %d\n",code);	
    // bit reverse the code
        code=reverse_bits(code);

    // check if beam code is reasonable
        if ( (code>8192) | (code<0) ){
                fprintf(stderr,"INVALID BEAM CODE - must be between 0 and 8192\n");
                return -1;
        }
    if (client->radar==1) {
      if (verbose > 1) printf("Selecting Radar 1 client block");
      portA=PA_GRP_0;
      portB=PB_GRP_0;
      portC=PC_GRP_0;
    }
    if (client->radar==2) {
      if (DEVICE_ID==0x0c78) {
        if (verbose > 1) printf("Selecting Radar 2 port block");
        portA=PA_GRP_2;
        portB=PB_GRP_2;
        portC=PC_GRP_2;
      } else {
        if (verbose > 1) printf("Radar 2 port block not available..using Radar 1 ports instead");
        portA=PA_GRP_0;
        portB=PB_GRP_0;
        portC=PC_GRP_0;
      }
    } 
#ifdef __QNX__
   // set CH0, Port A to lowest 8 bits of beam code and output on PortA
       temp=code & 0xff;
       out8(base+portA,temp);
   // set CH0, Port B to upper 5 bits of beam code and output on PortB
       temp=code & 0x1f00;
       temp=temp >> 8;
       out8(base+portB,temp);

   // verify that proper beam code was sent out
       temp=in8(base+portB);
       temp=(temp & 0x1f) << 8;
       temp=temp+in8(base+portA);
       if (temp==code) return 0;
       else{
               fprintf(stderr,"BEAM CODE OUTPUT ERROR - requested code not sent\n");
               return -1;
       }


/*
    // set CH0, Port A to lowest 8 bits of beam code and output on PortA

        temp=code & 0xff;
        out8(base+portA,temp);
    // save the upper bit (TM status) of Port B
        oldB=in8(base+portB);
        oldB=oldB & 0x80;
    // set CH0, lowest 5 bits on Port B to upper 5 bits of beam code
        temp=code & 0x1f00;
        temp=temp >> 8;
    // set CH0, bits 5-6 on Port B to lo bits of beamnum
        lo=lo << 5;
    // write code segment and saved bits back to Port B
        temp=oldB+temp+lo;
        out8(base+portB,temp);
        if (verbose > 1) printf("Port B code %d\n",temp);
    // save the lowest 6 bits of Port C
        oldC=in8(base+portC);
        oldC=oldC & 0x3F;
    // set CH0, bits 6-7 on Port C to hi bits of beamnum
        hi=hi << 6;
    // write code segment and saved bits back to Port B
        temp=oldC+hi;
        out8(base+portC,temp);
        if (verbose > 1 ) printf("Port C code %d\n",temp);

    // verify that proper beam code was sent out
        lo=in8(base+portB);
        lo=(lo & 0x60) >> 5;
        hi=in8(base+portC);
        hi=(hi & 0xC0) >> 4;
        temp=hi+lo;
        if (temp==beamnm) return 0;
        else{
                fprintf(stderr,"BEAMNM OUTPUT ERROR - requested beamnm not sent \n");
                fprintf(stderr,"%d %d %d %d\n",hi,lo,temp,beamnm);

                return -1;
        }

    // verify that proper code was sent out
        temp=in8(base+portB);
        temp=(temp & 0x1f) << 8;
        temp=temp+in8(base+portA);
        if (temp==code) return 0;
        else{
                fprintf(stderr,"BEAM CODE OUTPUT ERROR - requested code not sent \n");
                return -1;
        }
*/
#endif
        return code;
       
}
コード例 #23
0
ファイル: fft.c プロジェクト: RodolfoSeki/mc723_projeto3
int transform_radix2(float real[], float imag[], size_t n) {
	// Variables
	int status = 0;
	unsigned int levels;
	//float *cos_table, *sin_table;
	size_t size;
	size_t i;
	
	// Compute levels = floor(log2(n))
	{
		size_t temp = n;
		levels = 0;
		while (temp > 1) {
			levels++;
			temp >>= 1;
		}
		if (1u << levels != n)
			return 0;  // n is not a power of 2
	}
	
	// Trignometric tables
	if (N_MAX / sizeof(float) < n / 2)
		return 0;
	/*size = (n / 2) * sizeof(float);
	cos_table = malloc(size);
	sin_table = malloc(size);
	if (cos_table == NULL || sin_table == NULL)
		goto cleanup;
	for (i = 0; i < n / 2; i++) {
		cos_table[i] = cos(2 * M_PI * i / n);
		sin_table[i] = sin(2 * M_PI * i / n);
	}*/
	
	// Bit-reversed addressing permutation
	for (i = 0; i < n; i++) {
		size_t j = reverse_bits(i, levels);
		if (j > i) {
			float temp = real[i];
			real[i] = real[j];
			real[j] = temp;
			temp = imag[i];
			imag[i] = imag[j];
			imag[j] = temp;
		}
	}
	
	// Cooley-Tukey decimation-in-time radix-2 FFT
	for (size = 2; size <= n; size *= 2) {
		size_t halfsize = size / 2;
		size_t tablestep = n / size;
		for (i = 0; i < n; i += size) {
			size_t j;
			size_t k;
			for (j = i, k = 0; j < i + halfsize; j++, k += tablestep) {
				float tpre = sum_acc(mul_acc(real[j+halfsize], cos_mod_two(k,n)), mul_acc(imag[j+halfsize], sin_mod_two(k,n)));
				float tpim = sum_acc(mul_acc(-real[j+halfsize], sin_mod_two(k,n)), mul_acc(imag[j+halfsize], cos_mod_two(k,n)));
				real[j + halfsize] = sub_acc(real[j], tpre);
				imag[j + halfsize] = sub_acc(imag[j], tpim);
				real[j] = sum_acc(real[j],tpre);
				imag[j] = sum_acc(imag[j],tpim);
			}
		}
		if (size == n)  // Prevent overflow in 'size *= 2'
			break;
	}
	status = 1;
	
	
	
cleanup:
	//free(cos_table);
	//free(sin_table);
	return status;
}
コード例 #24
0
ファイル: hfcc_cpp.c プロジェクト: ozmemory/AudioFeExtr
void FFT_cpp(FFT_DATA_TYPE *a,FFT_DATA_TYPE *b,int m,int n_pts,int iff)
{	
	int n,id;
	unsigned i,j;
	unsigned k;
	unsigned BlockEnd=1;
	unsigned BlockSize;
	double tr,ti;
	double angle_numerator;
	double delta_angle;
	double sm2,sm1,cm2,cm1,w;
	double ar[3], ai[3];
	FFT_DATA_TYPE* c=(FFT_DATA_TYPE*)malloc(m*sizeof(FFT_DATA_TYPE));
    FFT_DATA_TYPE* d=(FFT_DATA_TYPE*)malloc(m*sizeof(FFT_DATA_TYPE));
	for(i=0;i<m;i++)
	{
		c[i]=0;
		d[i]=0;
	}
	//for(i=0;i<10;i++)
	//{
		//printf("a-->%f\n",a[i]);
		//printf("b-->%f\n",b[i]);
	//} no problem
	//printf("a:%f\n",a[3072]);
	for (i=0; i <n_pts; i++ )
    { 
      j=reverse_bits(i, 12);
	  //printf("%d\n",j);
      c[j]=a[i];
	  d[j]=b[i];
    }
	//for(i=0;i<10;i++)
	//{
		//printf("c-->%f\n",c[i]);
		//printf("d-->%f\n",d[i]);
	//}
	for( id=n_pts;id<m;id++)
	{	
      j = reverse_bits (id, 12);
	  c[j] =(double)0;
	  d[j]=(double)0;
	} 
	//for(i=2000;i<2100;i++)
	//{
		//printf("c-->%f\n",c[i]);
		//printf("d-->%f\n",d[i]);
	//} 
	for(BlockSize=2;BlockSize<=m;BlockSize<<=1)
	{	
	  angle_numerator = 2.0 * M_PI;
	  delta_angle = angle_numerator / (double)BlockSize;
      sm2 = sin ( 2.0 * delta_angle );
      sm1 = sin ( delta_angle );
      cm2 = cos ( 2.0 * delta_angle );
      cm1 = cos ( delta_angle );
       w = 2.0 * cm1;
      //for(i=0;i<3;i++)
	  //{
		//ar[i]=(double)0;
		//ai[i]=(double)0;
	  //}
	  for(i=0;i<m;i+=BlockSize)
	  { 
		ar[2] = cm2;
        ar[1] = cm1;

        ai[2] = sm2;
        ai[1] = sm1;
		for(j=i,n=0;n<BlockEnd;j++,n++)
		{ 	    
		  ar[0] = w*ar[1] - ar[2];
          ar[2] = ar[1];
          ar[1] = ar[0];

          ai[0] = w*ai[1] - ai[2];
          ai[2] = ai[1];
          ai[1] = ai[0];
		  k=0;
		  tr=0;
		  ti=0;
		  k = j + BlockEnd;
		  		    
          tr = ar[0]*c[k] - ai[0]*d[k];
		
          ti = ar[0]*d[k] + ai[0]*c[k];
		 //printf("ck:%f\n",c[k]);
          c[k] =c[j] - tr;
		  	//printf("--->ck:%f\n",c[k]);
		  d[k]=d[j]-ti;
		  c[j]+=tr;
		  d[j]+=ti;
		}
	  }
	  BlockEnd=BlockSize;
	}
	for(i=0;i<m;i++)
	{
		a[i]=0;
		b[i]=0;
	}
	for(i=0;i<m;i++)
	{
		a[i]=c[i];
		b[i]=d[i];
	}
	free(c);
	free(d);
}
コード例 #25
0
ファイル: fft.c プロジェクト: chlik/fft
int transform_radix2(double real[], double imag[], size_t n) {
	// Variables
	int status = 0;
	unsigned int levels;
	double *cos_table, *sin_table;
	size_t size;
	size_t i;
	
	// Compute levels = floor(log2(n))
	{
		size_t temp = n;
		levels = 0;
		while (temp > 1) {
			levels++;
			temp >>= 1;
		}
		if (1u << levels != n)
			return 0;  // n is not a power of 2
	}
	
	// Trignometric tables
	if (SIZE_MAX / sizeof(double) < n / 2)
		return 0;
	size = (n / 2) * sizeof(double);
	cos_table = malloc(size);
	sin_table = malloc(size);
	if (cos_table == NULL || sin_table == NULL)
		goto cleanup;
	for (i = 0; i < n / 2; i++) {
		cos_table[i] = cos(2 * M_PI * i / n);
		sin_table[i] = sin(2 * M_PI * i / n);
	}
	
	// Bit-reversed addressing permutation
	for (i = 0; i < n; i++) {
		size_t j = reverse_bits(i, levels);
		if (j > i) {
			double temp = real[i];
			real[i] = real[j];
			real[j] = temp;
			temp = imag[i];
			imag[i] = imag[j];
			imag[j] = temp;
		}
	}
	
	// Cooley-Tukey decimation-in-time radix-2 FFT
	for (size = 2; size <= n; size *= 2) {
		size_t halfsize = size / 2;
		size_t tablestep = n / size;
		for (i = 0; i < n; i += size) {
			size_t j;
			size_t k;
			for (j = i, k = 0; j < i + halfsize; j++, k += tablestep) {
				double tpre =  real[j+halfsize] * cos_table[k] + imag[j+halfsize] * sin_table[k];
				double tpim = -real[j+halfsize] * sin_table[k] + imag[j+halfsize] * cos_table[k];
				real[j + halfsize] = real[j] - tpre;
				imag[j + halfsize] = imag[j] - tpim;
				real[j] += tpre;
				imag[j] += tpim;
			}
		}
		if (size == n)  // Prevent overflow in 'size *= 2'
			break;
	}
	status = 1;
	
cleanup:
	free(cos_table);
	free(sin_table);
	return status;
}
コード例 #26
0
ファイル: fft.c プロジェクト: RodolfoSeki/mc723_projeto3
int transform_radix2(float real[], float imag[], size_t n, int procNumber) {
	// Variables
	int status = 0;
	unsigned int levels;
	//float *cos_table, *sin_table;
	size_t size;
	size_t i;

	// Compute levels = floor(log2(n))
	{
		size_t temp = n;
		levels = 0;
		while (temp > 1) {
			levels++;
			temp >>= 1;
		}
		if (1u << levels != n)
			return 0;  // n is not a power of 2
	}

	// Trignometric tables
	if (SIZE_MAX / sizeof(float) < n / 2)
		return 0;
	/*size = (n / 2) * sizeof(float);
	cos_table = malloc(size);
	sin_table = malloc(size);
	if (cos_table == NULL || sin_table == NULL)
		goto cleanup;
	for (i = 0; i < n / 2; i++) {
		cos_table[i] = cos(2 * M_PI * i / n);
		sin_table[i] = sin(2 * M_PI * i / n);
	}*/

	// Bit-reversed addressing permutation
	int start, end;
	getVectorParcel(&start,&end, n, procNumber);
	for (i = start; i < end; i++) {
		size_t j = reverse_bits(i, levels);
		if (j > i) {
			float temp = real[i];
			real[i] = real[j];
			real[j] = temp;
			temp = imag[i];
			imag[i] = imag[j];
			imag[j] = temp;
		}
	}
	incrementSemaphore(&firstSemaphore);
	acquireSemaphore(&firstSemaphore);

	// Cooley-Tukey decimation-in-time radix-2 FFT
	for (size = 2; size <= n; size *= 2) {
		size_t halfsize = size / 2;
		size_t tablestep = n / size;
		for (i = 0; i < n; i += size) {
			size_t j;
			size_t k;
			for (j = i, k = 0; j < i + halfsize; j++, k += tablestep) {
				float tpre =  real[j+halfsize] * cos_mod_two(k,n) + imag[j+halfsize] * sin_mod_two(k,n);
				float tpim = -real[j+halfsize] * sin_mod_two(k,n) + imag[j+halfsize] * cos_mod_two(k,n);
				real[j + halfsize] = real[j] - tpre;
				imag[j + halfsize] = imag[j] - tpim;
				real[j] += tpre;
				imag[j] += tpim;
			}
		}
		if (size == n)  // Prevent overflow in 'size *= 2'
			break;
	}
	status = 1;



cleanup:
	//free(cos_table);
	//free(sin_table);
	return status;
}
コード例 #27
0
ファイル: C5P3.c プロジェクト: clenk/School-Projects
main() {
    unsigned int value = 25;
    unsigned int result = 0;
    result = reverse_bits(value);
    printf("reverse %u is %u\n", value, result);
}
コード例 #28
0
ファイル: jedec.c プロジェクト: bsteinsbo/bonemachxo
int get_next_jedec_section(int *section, uint32_t *address, uint8_t **data, int *data_len)
{
	int c;
	int buffer_free;
	uint8_t *buffer;
	int buffer_ptr;
	int i;
	// Defaults
	*address = 0;
	*data = 0;
	*data_len = 0;
	while (!feof(f))
	{
		int c = getc(f);
		if (!is_ws(c))
		{
			ungetc(c, f);
			break;
		}
	}
	if (feof(f))
	{
		fprintf(stderr, "Truncated file\n");
		return 0;
	}
	c = getc(f);
	if (c == '\x03')
	{
		// End of file
		*section = SECTION_END;
		return 1;
	}
	else if (c == '*')
	{
		// empty section
		*section = SECTION_NONE;
		return 1;
	}
	// Assume valid JEDEC code.  Read data (skip white space)
	buffer_free = 80;
	buffer = (uint8_t*)malloc(buffer_free + 1);
	if (buffer == 0)
	{
		fprintf(stderr, "Out of memory\n");
		return 0;
	}
	buffer_ptr = 0;
	while (!feof(f))
	{
		int c = getc(f);
		if (c == '*')
			break;
		if (buffer_free == 0)
		{
			buffer_free = 2048;
			buffer = (uint8_t*)realloc(buffer, buffer_ptr + buffer_free + 1);
			if (buffer == 0)
			{
				fprintf(stderr, "Out of memory\n");
				return 0;
			}
		}
		buffer[buffer_ptr++] = c;
		--buffer_free;
	}
	buffer[buffer_ptr] = 0;
	if (feof(f))
	{
		fprintf(stderr, "Unexpected end of file\n");
		return 0;
	}
	switch (c)
	{
	case 'N':
		*section = SECTION_NOTE;
		*data = buffer;
		*data_len = buffer_ptr;
		return 1;
	case 'Q':
		if (buffer[0] == 'F')
		{
			*section = SECTION_NUM_FUSES;
			*data = buffer + 1;
			*data_len = buffer_ptr - 1;
		}
		else if (buffer[0] = 'P')
		{
			*section = SECTION_NUM_PINS;
			*data = buffer + 1;
			*data_len = buffer_ptr - 1;
		}
		else
		{
			fprintf(stderr, "Unknow field 'Q%c'\n", buffer[0]);
			return 0;
		}
		return 1;
	case 'F':
		*section = SECTION_DEFAULT_FUSE_VAL;
		*data = buffer;
		*data_len = 1;
		return 1;
	case 'G':
		*section = SECTION_SECURITY_FUSE;
		*data = buffer;
		*data_len = 1;
		return 1;
	case 'L':
		*section = SECTION_FUSE_MAP;
		*address = (uint32_t)strtol((char *)buffer, 0, 10);
		*address /= 8; // Byte address, not bit address
		for (i = 0; buffer[i] != '\n' && buffer[i] != 0; i++)
			;
		if (buffer[i] == 0)
		{
			fprintf(stderr, "Unexpected end of file\n");
			return 0;
		}
		*data = buffer + i + 1;
		*data_len = bitstring_to_bytes(*data);
		return 1;
	case 'C':
		*section = SECTION_CHECK_SUM;
		*data = buffer;
		*data_len = 4;
		return 1;
	case 'U':
		*section = SECTION_USERCODE;
		if (buffer[0] == 'A')
		{
			*address = buffer[4] + 0x100 * buffer[3] + 0x10000 * buffer[2] + 0x1000000 * buffer[1];
		}
		else if (buffer[0] == 'H')
		{
			*address = (uint32_t)strtoul((char *)(buffer + 1), 0, 16);
		}
		else
		{
			bitstring_to_bytes(buffer);
			*address = buffer[3] + 0x100 * buffer[2] + 0x10000 * buffer[1] + 0x1000000 * buffer[0];
		}
		return 1;
	case 'E':
		*section = SECTION_ARCH;
		*data = buffer;
		*data_len = bitstring_to_bytes(buffer);
		/* Incredibly enough, Lattice has managed to reverse the bits for features... */
		if (*data_len == 10)
		{
		  reverse_bits(*data, 8);
		  reverse_bits(*data + 8, 2);
		}
		else
		{
		  fprintf(stderr, "Unexpected data length '%d' for feature row/bits.  Expected 10 bytes.\n", *data_len);
		  return 0;
		}
		return 1;
	default:
		fprintf(stderr, "Unknown field '%c'\n", c);
		break;
	}
	return 0;
}
コード例 #29
0
ファイル: fft.c プロジェクト: jasonleaster/FFT
struct signal* fft(struct signal* p_signal)
{
	struct signal*  p_input_signal = \
	(struct signal*) malloc(sizeof(struct complex_number)*(p_signal->size) + sizeof(p_signal->size));

	struct signal*  p_out_put_signal = \
 	(struct signal*)malloc(sizeof(struct complex_number)*(p_signal->size) + sizeof(p_signal->size));

	*p_input_signal   = *p_signal;
	*p_out_put_signal = *p_signal;

	int tmp   = 0;
	int index = 0;
	int bits  = 0;

	int layyer= 0;
	int selected_point = 0;
	int pre_half	   = 0;	

	int    r  = 0;
	double x  = 0;
	struct complex_number W_rN ;
	struct complex_number complex_tmp ;

	/*
	**	We caculate how many bits should be used to 
	** represent the size of the number of input signal.
	*/
	for(tmp = p_signal->size-1;tmp > 0;tmp>>=1)
	{
		bits++;
	}

	/*
	**	We should re-sequence the input signal
	** by bit-reverse.
	*/
	for(tmp = 0;tmp < p_signal->size;tmp++)
	{
		index = reverse_bits(tmp,bits);
		p_input_signal->points[tmp] = p_signal->points[index];
#ifdef DEBUG
		printf(" tmp:%5d index:%5d  ",tmp,index);
		show_complex_number(&p_signal->points[index]);
#endif
	}

	for(layyer = 1;layyer <= bits;layyer++)
	{

		
		#ifdef DEBUG
			printf("layyer %d input\n",layyer);
			show_signal(p_input_signal);
		#endif

		for(selected_point = 0;selected_point < p_signal->size;selected_point += 1<<(layyer))
		{
			for(pre_half = selected_point,r = 0,x = 0;
			    pre_half < (selected_point + (1<<(layyer-1)));
			    pre_half++)
			{
				r = get_r_in_Wn(pre_half,layyer,bits);

				#ifdef DEBUG
					printf("r: %d\n",r);
				#endif
	
				x = -2*PI*r/((double)(p_input_signal->size));
				W_rN.real    = cos(x);
				W_rN.imagine = sin(x);

				complex_tmp = complex_mul(&W_rN , &(p_input_signal->points[pre_half + (1<<(layyer-1))])  );

				#ifdef DEBUG
					show_complex_number(&complex_tmp);
				#endif

				p_out_put_signal->points[pre_half] = \
				complex_add(&p_input_signal->points[pre_half],&complex_tmp);

				p_out_put_signal->points[pre_half + (1<<(layyer-1))] = \
				complex_sub(&p_input_signal->points[pre_half],&complex_tmp);

			}
			
		}

		#ifdef DEBUG
			printf("layyer%d output\n",layyer);
			show_signal(p_out_put_signal);
		#endif

		for(tmp = 0;tmp < p_out_put_signal->size;tmp++)
		{
			p_input_signal->points[tmp] = p_out_put_signal->points[tmp];
		}

	}

	free(p_input_signal);
	return p_out_put_signal;
}
コード例 #30
0
ファイル: Interrupts.c プロジェクト: ad-m/u2f-zero
SI_INTERRUPT (SMBUS0_ISR, SMBUS0_IRQn)
{
	data uint8_t bus = SMB0CN0 & SMB_STATE_MASK;
	data uint8_t c;
	if (SMB0CN0_ARBLOST != 0)
	{
		goto fail;
	}

	switch (bus)
	{
		case SMB_STATUS_START:
			SMB0DAT = SMB_addr | (SMB_FLAGS & SMB_READ);
			SMB0CN0_STA = 0;
			break;

		case SMB_STATUS_MTX:
			if (!SMB0CN0_ACK)
			{
				// NACK
				// end transaction
				SMB0CN0_STO = 1;
				SMB_FLAGS |= SMB_RECV_NACK;
				SMB_BUSY_CLEAR();
			}
			else if (!SMB_WRITING())
			{
				// do nothing and switch to receive mode
			}
			else if (SMB_write_offset < SMB_write_len)
			{
				// start writing first buffer
				// dont crc first byte for atecc508a
				c = SMB_write_buf[SMB_write_offset++];
				if (SMB_write_offset > 1) _feed_crc(c);
				SMB0DAT = c;

			}
			else if(SMB_WRITING_EXT() && SMB_write_ext_offset < SMB_write_ext_len)
			{
				// start writing second optional buffer
				c = SMB_write_ext_buf[SMB_write_ext_offset++];
				_feed_crc(c);
				SMB0DAT = c;
			}
			else
			{
				// write optional CRC
				switch(SMB_crc_offset++)
				{
					case 0:
						SMB_crc = reverse_bits(SMB_crc);
						SMB0DAT = (uint8_t)SMB_crc;
						break;
					case 1:
						SMB0DAT = (uint8_t)(SMB_crc>>8);
						break;
					case 2:
						SMB0CN0_STO = 1;
						SMB_BUSY_CLEAR();
				}
			}

			break;

		case SMB_STATUS_MRX:
			// read in buffer

			if (SMB_read_offset < SMB_read_len)
			{
				c = SMB0DAT;
				SMB_read_buf[SMB_read_offset] = c;

				// update with length from packet
				// warning this is device specific to atecc508a
				if (SMB_read_offset == 0)
				{
					update_from_packet_length();
				}

				if ((SMB_read_offset < (SMB_read_len - 2)))
				{
					SMB_crc = feed_crc(SMB_crc, c);
				}

				SMB_read_offset++;
				SMB0CN0_ACK = 1;
			}
			else
			{
				// end transaction

				SMB_crc = reverse_bits(SMB_crc);
				SMB_BUSY_CLEAR();
				SMB0CN0_ACK = 0;
				SMB0CN0_STO = 1;
			}

			break;

		default:
			goto fail;
			break;

	}


	// interrupt flag
	SMB0CN0_SI = 0;
	return;

	fail:
		u2f_printb("smbus fail ",1,bus);
		//restart_bus();
		SMB0CN0_SI = 0;
}