I am creating a simple C application using GCC in Ubuntu based on Conway's Game of Life. I have basically all the code that I need, but I'm having trouble with one tiny aspect of the code.
My C source file:
#include <stdio.h>
#include <stdlib.h>
#define HEIGHT 32
#define WIDTH 32
#define COMPASS 8
#define SPACE '.'
unsigned long mask = 0x80000000;
unsigned long row[WIDTH] = { 0 };
unsigned long copy[WIDTH] = { 0 };
int northWest(int rowNum) {
copy[rowNum - 1] = row[rowNum - 1] >>= 1;
return copy[rowNum - 1] & row[rowNum];
}
int north(int rowNum) {
copy[rowNum - 1] = row[rowNum - 1];
return copy[rowNum - 1] & row[rowNum];
}
int northEast(int rowNum) {
copy[rowNum - 1] = row[rowNum - 1] <<= 1;
return copy[rowNum - 1] & row[rowNum];
}
int west(int rowNum) {
copy[rowNum] = row[rowNum] >>= 1;
return copy[rowNum] & row[rowNum];
}
int east(int rowNum) {
copy[rowNum] = row[rowNum] <<= 1;
return copy[rowNum] & row[rowNum];
}
int southWest(int rowNum) {
copy[rowNum + 1] = row[rowNum + 1] >>= 1;
return copy[rowNum + 1] & row[rowNum];
}
int south(int rowNum) {
copy[rowNum + 1] = row[rowNum];
return copy[rowNum + 1] & row[rowNum];
}
int southEast(int rowNum) {
copy[rowNum + 1] = row[rowNum + 1] <<= 1;
return copy[rowNum + 1] & row[rowNum];
}
void clearRows(unsigned long row[]) {
int i;
system("clear");
for (i = 0; i < HEIGHT; ++i) {
row[i] = 0;
}
}
void displayBinary(unsigned long x) {
int bit;
/*int mask;*/
for (bit = 0; bit < HEIGHT; ++bit)
{
mask = 1 << bit;
printf("%c", (x & mask) ? 'X' : SPACE);
}
printf("\n");
}
int main(void) {
int i, j, alive;
char ch;
unsigned long init32;
srand(time(NULL));
for (i = 0; i < HEIGHT; ++i) {
init32 = ((double)rand() / RAND_MAX) * 0xFFFFFFFF;
row[i] = init32;
displayBinary(row[i]);
}
do {
system("clear");
for (i = 0; i < WIDTH; ++i) {
unsigned long neighbours[COMPASS] = {
north(i),
south(i),
west(i),
east(i),
northEast(i),
northWest(i),
southEast(i),
southWest(i)
};
for (j = 0; j < COMPASS; ++j) {
alive += ((mask & neighbours[j]) ? 1 : 0);
}
displayBinary(row[i]);
}
} while ((ch = getchar()) != 'n');
return EXIT_SUCCESS;
}
When the application first starts, the output is what I expect (a 32x32 grid of random 'X' and '.' chars), but for each iteration after that, nothing changes. I want each loop to re-calculate neighbours based on the methods I have (north(), west(), etc...) and print the new 'X' and '.' values on the 32x32 grid.
Can anybody offer some sort of assistance on how to get the new values into the array to be printed on screen? I'm new to programming in C by the way. Thanks.
I do not see where you are updating your row array anywhere in the code. Should not you be updating that in your do while loop ?
Okay I see in your function like one copied below, you are using row >>= 1 to change row as well. But since you are using pass by value instead of pass by reference, the original row value remains unchanged.
int northWest(unsigned long row, int rowNum) {
copy[rowNum - 1] = row >>= 1;
return copy[rowNum - 1];
}
You can use pass by value to fix that.
OR
Since your row array is global, you can change it directly in these functions using the rowNum (index) which you are passing.
Related
i have this code:
if (is_prime == 1) {
for (marsennloop = 1, marsenn = 0; marsennloop <= calc; marsennloop++) {
marsennloop = marsennloop * 2;
marsenncalc2 = marsennloop - 1;
if (marsenncalc2 == calc && calc != 1) {
marsenn = 1;
}
}
}
on the line "marsennloop = marsennloop * 2;" i am trying to do a pow function without using pow but this give me an incorrect output when i change this line to pow and use the same variables i get the correct output which leads me to believe the problem lies within that line of code.
power of two (2^n) is simply shift 1 << n
So naive function checking if the number is mersenne prime:
int ism(unsigned val)
{
int result = 0;
for(unsigned long long i = 2; i <= 1ULL << (CHAR_BIT * sizeof(val)); i <<= 1)
{
if(i - 1 == val)
{
result = 1;
break;
}
}
return result;
}
int main(void)
{
unsigned count = 0;
for(unsigned i = 1; i <= (1U << 20); i++)
{
if(ism(i))
{
printf("%u ", i);
if(!(++count % 16)) printf("\n");
}
}
}
If you want to test if the number is 2^n - 1, please try the following function:
int is_m(unsigned int x)
{
return (x & (x + 1)) == 0;
}
It returns 1 if x is 2^n - 1, else returns 0.
I just started using a microcontroller and I have to implement encryption/decryption in it. Sorry for the super long post.
This is the python script and do not need to be edited.
DEVPATH = "/dev"
TTYPREFIX = "ttyACM"
INPUT = b"Hello!"
#OUTPUT = b"Ifmmp!"
if __name__=='__main__':
for tty in (os.path.join(DEVPATH,tty) for tty in os.listdir(DEVPATH) \
if tty.startswith(TTYPREFIX)):
try:
ctt = serial.Serial(tty, timeout=1, writeTimeout=1)
except serial.SerialException:
continue
ctt.flushInput()
ctt.flushOutput()
# print(ctt)
try:
ctt.write(INPUT)
except serial.SerialTimeoutException:
ctt.__exit__()
continue
for retry in range(3): # Try three times to read connection test result
ret = ctt.read(2*len(INPUT))
print("ret: " + repr(ret))
if INPUT in ret:
sys.exit(0)
break
else:
ctt.__exit__()
continue
break
else:
print("Failed")
sys.exit(1)
This is the main.c file. I know that CDC_Device_BytesReceived will receive the input from the python script. And if there are input, it will run the while loop since Bytes will be more than 0.
while (1)
{
/* Check if data received */
Bytes = CDC_Device_BytesReceived(&VirtualSerial_CDC_Interface);
while(Bytes > 0)
{
/* Send data back to the host */
ch = CDC_Device_ReceiveByte(&VirtualSerial_CDC_Interface);
CDC_Device_SendByte(&VirtualSerial_CDC_Interface, ch);
--Bytes;
}
CDC_Device_USBTask(&VirtualSerial_CDC_Interface);
}
return 0;
}
However, in the loop, I was tasked to add a switch case so that it will switch between encryption and decryption. But I have no idea what kind of condition to use to differentiate the encryption and decryption.
This is the code for encryption.
int crypto_aead_encrypt(unsigned char* c, unsigned long long* clen,
const unsigned char* m, unsigned long long mlen,
const unsigned char* ad, unsigned long long adlen,
const unsigned char* nsec, const unsigned char* npub,
const unsigned char* k)
{
int klen = CRYPTO_KEYBYTES; // 16 bytes
int size = 320 / 8; // 40 bytes
int rate = 128 / 8; // 16 bytes
// int capacity = size - rate;
// Permutation
int a = 12;
int b = 8;
// Padding process appends a 1 to the associated data
i64 s = adlen / rate + 1;
// Padding process appends a 1 to the plain text
i64 t = mlen / rate + 1;
// Length = plaintext mod r
// i64 l = mlen % rate;
u8 S[size];
// Resulting Padded associated data is split into s blocks of r bits
u8 A[s * rate];
// Resulting Padded plain text is split into t blocks of r bits
u8 P[t * rate];
i64 i, j;
// Pad Associated Data
for(i = 0; i < adlen; ++i)
{
A[i] = ad[i];
A[adlen] = 0x80; // 128 bits
// No Padding Applied
for(i = adlen + 1; i < s * rate; ++i)
{
A[i] = 0;
}
}
// Pad Plaintext
for(i = 0; i < mlen; ++i)
{
P[i] = m[i];
P[mlen] = 0x80; // 128 bits
// No Padding Applied
for(i = mlen + 1; i < t * rate; ++i)
{
P[i] = 0;
}
}
// Initialization
// IV = k || r || a || b || 0
// S = IV || K || N
S[0] = klen * 8;
S[1] = rate * 8;
S[2] = a;
S[3] = b;
// i < 40 - 2 * 16 = 8
for(i = 4; i < size - 2 * klen; ++i)
{
// S[4] until S[7] = 0
S[i] = 0;
}
// i < 16
for(i = 0; i < klen; ++i)
{
// S[8] = k[0], S[9] = k[1] until S[23] = k[15]
S[size - 2 * klen + i] = k[i];
}
// i < 16
for(i = 0; i < klen; i++)
{
// S[24] = npub[0], S[25] = npub[1] until S[39] = npub[15]
S[size - klen + i] = npub[i];
}
printstate("Initial Value: ", S);
// S - state, 12-a - start, a - 12 rounds
permutations(S, 12 - a, a);
// i < 16
for(i = 0; i < klen; ++i)
{
// S[24] ^= k[0], S[25] ^= k[1] until S[39] ^= k[15]
S[size - klen + i] ^= k[i];
}
printstate("Initialization: ", S);
// Process Associated Data
if(adlen != 0)
{
// i < s = (adlen / rate + 1)
for(i = 0; i < s; ++i)
{
// rate = 16
for(j = 0; j < rate; ++i)
{
// S ^= A
S[j] ^= A[i * rate + j];
}
// S - state, 12-b - start, b - 8 rounds
permutations(S, 12 - b, b);
}
}
// S <- S ^= 1
S[size - 1] ^= 1;
printstate("Process Associated Data: ", S);
// Process Plain Text
for(i = 0; i < t - 1; ++i)
{
for(j = 0; j < rate; ++j)
{
// S <- S ^= P
S[j] ^= P[i * rate + j];
// c <- S
c[i * rate + j] = S[j];
}
// S <- permutation b (S)
permutations(S, 12 - b, b);
}
for(j = 0; j < rate; ++j)
{
// S <- S ^= Pt
S[j] ^= P[(t-1) * rate + j];
}
for(j = 0; j < 1; ++j);
{
// C <- S
// Bitstring S truncated to the first (most significant) k bits
c[(t - 1) * rate + j] = S[j];
}
printstate("Process Plaintext: ", S);
// Finalization
for(i = 0; i < klen; ++i)
{
S[rate + i] ^= k[i];
}
permutations(S, 12 - a, a);
for(i = 0; i < klen; ++i)
{
// T <- S ^= k
// Bitstring S truncated to the last (least significant) k bits
S[size - klen + i] ^= k[i];
}
printstate("Finalization: ", S);
// Return Cipher Text & Tag
for(i = 0; i < klen; ++i)
{
c[mlen + i] = S[size - klen + i];
}
*clen = mlen + klen;
return 0;
}
and the code for decryption
int crypto_aead_decrypt(unsigned char *m, unsigned long long *mlen,
unsigned char *nsec, const unsigned char *c,
unsigned long long clen, const unsigned char *ad,
unsigned long long adlen, const unsigned char *npub,
const unsigned char *k)
{
*mlen = 0;
if (clen < CRYPTO_KEYBYTES)
return -1;
int klen = CRYPTO_KEYBYTES;
// int nlen = CRYPTO_NPUBBYTES;
int size = 320 / 8;
int rate = 128 / 8;
// int capacity = size - rate;
int a = 12;
int b = 8;
i64 s = adlen / rate + 1;
i64 t = (clen - klen) / rate + 1;
i64 l = (clen - klen) % rate;
u8 S[size];
u8 A[s * rate];
u8 M[t * rate];
i64 i, j;
// pad associated data
for (i = 0; i < adlen; ++i)
{
A[i] = ad[i];
}
A[adlen] = 0x80;
for (i = adlen + 1; i < s * rate; ++i)
{
A[i] = 0;
}
// initialization
S[0] = klen * 8;
S[1] = rate * 8;
S[2] = a;
S[3] = b;
for (i = 4; i < size - 2 * klen; ++i)
{
S[i] = 0;
}
for (i = 0; i < klen; ++i)
{
S[size - 2 * klen + i] = k[i];
}
for (i = 0; i < klen; ++i)
{
S[size - klen + i] = npub[i];
}
printstate("initial value:", S);
permutations(S, 12 - a, a);
for (i = 0; i < klen; ++i)
{
S[size - klen + i] ^= k[i];
}
printstate("initialization:", S);
// process associated data
if (adlen)
{
for (i = 0; i < s; ++i)
{
for (j = 0; j < rate; ++j)
{
S[j] ^= A[i * rate + j];
}
permutations(S, 12 - b, b);
}
}
S[size - 1] ^= 1;
printstate("process associated data:", S);
// process plaintext
for (i = 0; i < t - 1; ++i)
{
for (j = 0; j < rate; ++j)
{
M[i * rate + j] = S[j] ^ c[i * rate + j];
S[j] = c[i * rate + j];
}
permutations(S, 12 - b, b);
}
for (j = 0; j < l; ++j)
{
M[(t - 1) * rate + j] = S[j] ^ c[(t - 1) * rate + j];
}
for (j = 0; j < l; ++j)
{
S[j] = c[(t - 1) * rate + j];
S[l] ^= 0x80;
}
printstate("process plaintext:", S);
// finalization
for (i = 0; i < klen; ++i)
{
S[rate + i] ^= k[i];
}
permutations(S, 12 - a, a);
for (i = 0; i < klen; ++i)
{
S[size - klen + i] ^= k[i];
}
printstate("finalization:", S);
// return -1 if verification fails
for (i = 0; i < klen; ++i)
{
if (c[clen - klen + i] != S[size - klen + i])
{
return -1;
}
}
// return plaintext
*mlen = clen - klen;
for (i = 0; i < *mlen; ++i)
{
m[i] = M[i];
}
return 0;
}
Thanks for the help in advance, I am really clueless right now.
However, in the loop, I was tasked to add a switch case so that it
will switch between encryption and decryption. But I have no idea what
kind of condition to use to differentiate the encryption and
decryption.
According to your comments, the calls for encryption and decryption are happening inside of CDC_Device_ReceiveByte and CDC_Device_SendByte, which means you need to create a state machine for sending and receiving of the bytes. The condition that you would use for this is the return value of CDC_Device_BytesReceived.
You can create an enum for the states, and a simple struct for holding the current state along with any other pertinent information. You can create a function for the state machine that maps out what to do given the current state. Your while(1) loop will simply call the function to ensure the state machine moves along. You might implement that like this:
typedef enum{
IDLE,
DECRYPTING,
ENCRYPTING,
}state_t;
typedef struct{
state_t current_state;
}fsm_t;
fsm_t my_fsm = {0}; //initial state is idle
void myFSM(void){
switch(my_fsm.current_state){
case IDLE:
{
/* Check if data received */
Bytes = CDC_Device_BytesReceived(&VirtualSerial_CDC_Interface);
if(Bytes) my_fsm.current_state = DECRYPTING; //we have data, decrypt it
break;
}
case DECRYPTING:
{
/* Send data back to the host */
ch = CDC_Device_ReceiveByte(&VirtualSerial_CDC_Interface);
my_fsm.current_state = ENCRYPTING; // encrypt byte that we are going to send to host
break;
}
case ENCRYPTING:
{
CDC_Device_SendByte(&VirtualSerial_CDC_Interface, ch);
--Bytes;
if(Bytes){
my_fsm.current_state = DECRYPTING; // still have bytes left to decrypt
}
else my_fsm.current_state = IDLE;
break;
}
default:
{
asm("nop"); // whoops
break;
}
}
}
Now your loop is just
while(1){
myFSM();
}
I have matrix of '1' and '0' with the dimensions 8x8. I need to store the whole matrix in one unsigned long long variable bit by bit. How can i do that?
For example, let's take the matrix of '1' and '0' that is 2x2:
The matrix 2x2:
1 0
0 1
The variable must contain: 1001 in bits.
The same example, but over the matrix 8x8 and unsigned long long variable.
That's what i've tried to do:
#include <stdio.h>
int main()
{
unsigned long long result = 0;
char matrix[8][8]; // lets that the matrix is already filled by '1' and '0'
for (i=0; i<SIZE; i++)
{
for (j=0; j<SIZE; j++)
{
result = result | ((unsigned long long)(matrix[i][j] - '0'));
result <<= 1;
}
}
return 0;
}
Is it right? I implemented this nested loop in my algorithm and that didn't work properly.
Converting the text representation of an integer into its integer value can be done using strtoull().
char buf[sizeof(matrix)+1];
memcpy(buf, matrix, sizeof(matrix));
buf[sizeof(matrix)] = '\0';
result = strtoull(buf, NULL, 2);
try this
const int mx_size = 8;
int main() {
unsigned long long result = 0;
bool matrix[8][8]; // lets that the matrix is already filled by '1' and '0'
for (int i =0; i < mx_size; ++i)
matrix[i][i] = 1;
for (int i = 0; i < mx_size; i++) {
for (int j = 0; j < mx_size; j++) {
result |= (unsigned long long)matrix[i][j] << (i*mx_size + j);
}
}
return 0;
}
Here you have the code (a bit more
#include <stdio.h>
#include <stdint.h>
uint64_t convert(char matrix[8][8], int order, char zero)
{
uint8_t byte;
uint64_t result = 0;
for(size_t row = 0; row < 8; row++)
{
byte = 0;
for(size_t column = 0; column < 8; column++)
{
byte <<= 1;
byte |= matrix[row][column] != zero ? 1 : 0; //anything != defined zero char is 1
}
if (order)
{
result |= (uint64_t)byte << (8 * row);
}
else
{
result |= (uint64_t)byte << (56 - 8 * row);
}
}
return result;
}
int main(void) {
char matrix[8][8] =
{
{'1','0','1','0','1','0','1','0'},
{'0','1','0','1','0','1','0','1'},
{'1','1','1','0','0','0','1','1'},
{'0','0','0','1','1','1','0','0'},
{'1','1','1','1','1','0','0','0'},
{'0','0','0','0','1','1','1','1'},
{'1','1','0','0','1','1','0','0'},
{'0','0','1','1','0','0','1','1'},
};
unsigned long long result = convert(matrix, 0, '0');
for(size_t index = 0; index < 64; index ++)
printf("%1d", !!(result & (1ULL << index)));
printf("\n");
result = convert(matrix,1, '0');
for(size_t index = 0; index < 64; index ++)
printf("%1d", !!(result & (1ULL << index)));
printf("\n");
return 0;
}
I have to print numbers with max N bits where count of bits set to 1 = count of bits set to 0. I ignoring leading zeros. I thinking that this applies only when count of bits is even.
My code:
int power(k) {
return 1 << k;
}
void print_numbers(int n){
n -= (n % 2); // FOR EVEN COUNT OF BITS
int exp = 1; // EXPONENTS WILL BE ODD (2^1, 2^3, 2^5, ...)
while (exp < n) {
int start = power(exp);
int end = power(exp + 1);
int ones = (exp + 1) / 2; // ALLOWED COUNT OF 1
for (int i = start; i < end; i++) {
int bits_count = 0;
for (int j = 0; j <= exp; j++){ // CHECK COUNT OF 1
bits_count += ((i >> j) & 1);
}
if (bits_count == ones){
printf("%d\n", i);
}
}
exp += 2;
}
For N = 12 this function print 637 numbers. Is this solution correct or am i wrong? Any idea for more efficient or better solution?
I came up with this, which is a totally different approach (and perfectible) but works:
#include <stdio.h>
void checker(int number)
{
int c;
int zeros = 0;
int ones = 0;
for (c = 31; c >= 0; c--)
{
if (number >> c & 1)
{
ones++;
}
else if(ones > 0)
{
zeros++;
}
}
if(zeros == ones)
{
printf("%i\n", number);
}
}
int main()
{
int c;
for (c = 4095; c >= 0; c--)
{
checker(c);
}
return 0;
}
Which get me 638 values (including 0)
I am building a version of the Game of Life in ANSI C and I have almost all of the code written for it.
My C source file:
#include <stdio.h>
#include <stdlib.h>
#define HEIGHT 32
#define WIDTH 32
#define COMPASS 8
#define SPACE '.'
unsigned long mask = 0x80000000;
unsigned long neighbours[COMPASS] = { 0 };
unsigned long row[WIDTH] = { 0 };
unsigned long copy[WIDTH] = { 0 };
int northWest(unsigned long row, int rowNum) {
copy[rowNum - 1] = row >>= 1;
return copy[rowNum - 1];
}
int north(unsigned long row, int rowNum) {
copy[rowNum - 1] = row;
return copy[rowNum - 1];
}
int northEast(unsigned long row, int rowNum) {
copy[rowNum - 1] = row <<= 1;
return copy[rowNum - 1];
}
int west(unsigned long row, int rowNum) {
copy[rowNum] = row >>= 1;
return copy[rowNum];
}
int east(unsigned long row, int rowNum) {
copy[rowNum] = row <<= 1;
return copy[rowNum];
}
int southWest(unsigned long row, int rowNum) {
copy[rowNum + 1] = row >>= 1;
return copy[rowNum + 1];
}
int south(unsigned long row, int rowNum) {
copy[rowNum + 1] = row;
return copy[rowNum + 1];
}
int southEast(unsigned long row, int rowNum) {
copy[rowNum + 1] = row <<= 1;
return copy[rowNum + 1];
}
/*void clearRows(unsigned long row[]) {
int i;
system("clear");
for (i = 0; i < HEIGHT; ++i) {
row[i] = 0;
}
}*/
void displayBinary(unsigned long x) {
int bit;
int mask;
for (bit = 0; bit < HEIGHT; ++bit) {
mask = 1 << bit;
printf("%c", (x & mask) ? 'X' : SPACE);
}
printf("\n");
}
int main(void) {
int i, alive;
char ch;
unsigned long init32;
srand(time(NULL));
for (i = 0; i < HEIGHT; ++i) {
init32 = ((double)rand() / RAND_MAX) * 0xFFFFFFFF;
row[i] = init32;
displayBinary(row[i]);
}
do {
system("clear");
for (i = 0; i < HEIGHT; ++i) {
neighbours[0] = north(row[i], i);
neighbours[1] = south(row[i], i);
neighbours[2] = west(row[i], i);
neighbours[3] = east(row[i], i);
neighbours[4] = northWest(row[i], i);
neighbours[5] = northEast(row[i], i);
neighbours[6] = southEast(row[i], i);
neighbours[7] = southWest(row[i], i);
}
for (i = 0; i < HEIGHT; ++i) {
alive += ((mask & neighbours[i]) ? 1 : 0);
displayBinary(row[i]);
}
} while ((ch = getchar()) != 'n');
return EXIT_SUCCESS;
}
What I am aiming for here is to have random 'X' characters printed on a 32x32 board, and have the program loop as long as the user does not type 'n'. For each loop iteration, I would like each coordinate to check its neighbours and "die" if it has less than two neighbours or more than three neighbours. Otherwise, it "lives" and an 'X' is printed at that coordinate.
I understand using bitwise ANDing may not be the best way to complete this, but my professor has asked we use bitwise AND, and so therefore I cannot change that logic.
I am having trouble clearing the rows between loops. Could somebody please help me figure out how to print the updated rows for each iteration of the do loop?
Any help is much appreciated. Thank you.
In order to show what is going on, I added this define,
//#define SPACE (0x20)
#define SPACE ('.')
Then I changed both instances where you printed space,
printf("%c", 0x20);
to
printf("%c", SPACE);
And then ran your program and got a single line, with some "." and some "X", but the second pass resulted in all ".",
Looks like your calculation of adjacent nodes might be wrong.
Why does your print appear wrong?
Because your first COMPASS loop uses displayBinary() 8 times,
for (i = 0; i < COMPASS; ++i) {
init32 = ((double)rand() / RAND_MAX) * 0xFFFFFFFF;
row[i] = init32;
displayBinary(row[i]);
}
While your subsequent looks use printf (rather than calling displayBinary), 8 times to only print 8 characters,
for (i = 0; i < COMPASS; ++i) {
alive += ((mask & row[i]) ? 1 : 0);
if ((alive == 2) || (alive == 3))
printf("%c", 'X');
else
printf("%c", SPACE);
}
Your HEIGHT loop does a recalculation of neighbours[], but you should be reseting row[].
I rewrote your displayBinary function, and this displays the entire row,
void displayBinary(unsigned long x) {
//do {
// printf("%c", (x & mask) ? 'X' : SPACE);
//} while ((mask >>= 1) != 0);
int bit;
int mask;
for( bit=0; bit<32; ++bit )
{
mask = 1<<bit;
printf("%c", (x & mask) ? 'X' : SPACE);
}
printf("\n");
}