Skip to main content

replaceString

Nov 14, 2021LeifMessinger
Loading...

More C Posts

Fast inverse square root

Nov 19, 2022CodeCatch

0 likes • 0 views

// The following code is the fast inverse square root implementation from Quake III Arena
// this code has been stripped of C preprocessor directives, but includes the exact original comment text
float Q_rsqrt( float number )
{
long i;
float x2, y;
const float threehalfs = 1.5F;
x2 = number * 0.5F;
y = number;
i = * ( long * ) &y; // evil floating point bit level hacking
i = 0x5f3759df - ( i >> 1 ); // what the fuck?
y = * ( float * ) &i;
y = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration
// y = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed
return y;
}

Bitwise operators with pointers

Nov 18, 2022AustinLeath

0 likes • 0 views

#include <stdio.h>
#include <stdlib.h>
int main(){
int * int_ptr;
int_ptr = (int *)malloc(2*sizeof(int));
if(!int_ptr) {
printf("Something went wrong while allocating memory. Exiting...");
exit(1);
}
printf("Enter first integer: ");
scanf("%i", &int_ptr[0]);
printf("Enter second integer: ");
scanf("%i", &int_ptr[1]);
printf("Original values: 1st = %i 2nd = %i\n",int_ptr[0], int_ptr[1]);
int_ptr[0] = int_ptr[0] ^ int_ptr[1];
//printf("%i\n", int_ptr[0]);
int_ptr[1] = int_ptr[0] ^ int_ptr[1];
//printf("%i\n", int_ptr[1]);
int_ptr[0] = int_ptr[0] ^ int_ptr[1];
//printf("%i\n", int_ptr[0]);
printf("Swapped values: 1st = %i 2nd = %i\n", int_ptr[0], int_ptr[1]);
free(int_ptr);
exit(0);
}

socketUDPPingClient.c

Aug 5, 2023LeifMessinger

0 likes • 3 views

// Client side implementation of UDP client-server model
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#define PORT 8008
#define MAXLINE 1024
// Driver code
int main() {
char buffer[MAXLINE];
struct sockaddr_in servaddr;
// Creating socket file descriptor
int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if ( sockfd < 0 ) {
perror("socket creation failed");
exit(EXIT_FAILURE);
}
struct timeval timeout;
timeout.tv_sec = 1; //Wait 1 second
timeout.tv_usec = 0;
if (setsockopt (sockfd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof timeout) < 0) perror("setsockopt failed\n");
if (setsockopt (sockfd, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof timeout) < 0) perror("setsockopt failed\n");
memset(&servaddr, 0, sizeof(servaddr));
// Filling server information
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(PORT);
servaddr.sin_addr.s_addr = inet_addr("192.168.4.65");
for(int i = 0; i < 10; ++i){
char* message = "PING";
int sendStatus = sendto(sockfd, (const char *)message, strlen(message), MSG_CONFIRM, (const struct sockaddr *) &servaddr, sizeof(servaddr));
if(sendStatus >= 0){
printf("Sent PING\n");
}else{
printf("Send failed\n");
continue;
}
int len = sizeof(struct sockaddr_in);
int bytesRecieved = recvfrom(sockfd, (char *)buffer, MAXLINE, MSG_WAITALL, (struct sockaddr *) &servaddr, &len); //We can reuse servaddr because the port the server sends messages from is the same one we send to
if(bytesRecieved >= 0){
buffer[bytesRecieved] = '\0';
printf("Recieved %s\n", buffer);
}else{
printf("Recieved nothing: Packet Dropped\n", buffer);
}
}
close(sockfd);
return 0;
}

wait() example

Nov 19, 2022CodeCatch

0 likes • 0 views

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main() {
char * cmd[] = {
"who",
"ls",
"date"
};
int i;
while (1) {
printf("0=who 1=ls 2=date : ");
scanf("%d", & i);
if (fork() == 0) {
/* child */
execlp(cmd[i], cmd[i], (char * ) 0);
printf("execlp failed\n");
exit(1);
} else {
/* parent */
wait((int * ) 0);
printf("child finished\n");
}
} /* while */
} /* main */

Arduino Sound Demo

Jan 4, 2022LeifMessinger

0 likes • 1 view

//Leif Messinger
const int BUZZER_PIN = 8;
const int BUTTON_PIN = 2;
const int BUTTON_PINMODE = INPUT_PULLUP;
#define DEBOUNCE_DELAY 50
class Button{
private:
short buttonPin;
bool buttonState;
bool lastButtonState;
int lastDebounceTime;
public:
Button(short buttonPin): buttonState(HIGH), lastButtonState(LOW), lastDebounceTime(millis()){
this->buttonPin = buttonPin;
}
bool checkForPress(const bool desiredState){ //Returns true if button pressed
bool reading = (bool)digitalRead(buttonPin);
// check to see if you just pressed the button
// (i.e. the input went from LOW to HIGH), and you've waited long enough
// since the last press to ignore any noise:
// If the switch changed, due to noise or pressing:
if (reading != lastButtonState) {
// reset the debouncing timer
lastDebounceTime = millis();
}else if ((millis() - lastDebounceTime) > DEBOUNCE_DELAY) {
// whatever the reading is at, it's been there for longer than the debounce
// delay, so take it as the actual current state:
// if the button state has changed:
if (reading != buttonState) {
buttonState = reading;
// only toggle the LED if the new button state is HIGH
if (buttonState == desiredState) {
return true;
}
}
}
// save the reading. Next time through the loop, it'll be the lastButtonState:
lastButtonState = reading;
return false;
}
void waitForPress(const bool desiredState){
while(!checkForPress(desiredState));
}
};
class Note{
public:
short frequency; //Short max is ~ 30k, so way higher than you can hear
short lag; //Also 30k ms is 30 seconds
float sustainPercentage;
};
const short normalBeatLength = 500;
const short wholeNote = 4*normalBeatLength;
const short halfNote = 2*normalBeatLength;
const short dottedQuarterNote = normalBeatLength + (normalBeatLength / 2);
const short quarterNote = normalBeatLength;
const short dottedEighthNote = ((3 * normalBeatLength) / 4);
const short eighthNote = normalBeatLength/ 2;
const short sixteenthNote = normalBeatLength / 4;
const float normalSustainLength = .25;
void beep(const Note& note){ //It might go terribly wrong if you try to beep two tones at the same time.
tone(BUZZER_PIN, note.frequency);
delay(note.lag * note.sustainPercentage);
noTone(BUZZER_PIN);
delay(note.lag * (1.0 - note.sustainPercentage));
}
Note song[] = {
{(int)523.25, halfNote, normalSustainLength},
{(int)392, eighthNote, normalSustainLength},
{(int)523.25, quarterNote, normalSustainLength},
{(int)392, dottedEighthNote, normalSustainLength},
{(int)440.00, sixteenthNote, normalSustainLength},
{(int)493.88, quarterNote, normalSustainLength},
{(int)329.63, eighthNote, normalSustainLength},
{(int)329.63, eighthNote, normalSustainLength},
{(int)440.00, quarterNote, normalSustainLength},
{(int)392, dottedEighthNote, normalSustainLength},
{(int)349.23, sixteenthNote, normalSustainLength},
{(int)392, quarterNote, normalSustainLength},
{(int)261.63, dottedEighthNote, normalSustainLength},
{(int)261.63, sixteenthNote, normalSustainLength},
{(int)293.66, quarterNote, normalSustainLength},
{(int)293.66, dottedEighthNote, normalSustainLength},
{(int)329.63, sixteenthNote, normalSustainLength},
{(int)349.23, quarterNote, normalSustainLength},
{(int)349.23, dottedEighthNote, normalSustainLength},
{(int)392.00, sixteenthNote, normalSustainLength},
{(int)440.00, quarterNote, normalSustainLength},
{(int)493.88, eighthNote, normalSustainLength},
{(int)523.25, eighthNote, normalSustainLength},
{(int)587.33, dottedQuarterNote, normalSustainLength},
{(int)392, eighthNote, normalSustainLength},
{(int)659.25, quarterNote, normalSustainLength},
{(int)587.33, dottedEighthNote, normalSustainLength},
{(int)523.25, sixteenthNote, normalSustainLength},
{(int)587.33, quarterNote, normalSustainLength},
{(int)493.88, eighthNote, normalSustainLength},
{(int)392, eighthNote, normalSustainLength},
{(int)523.25, quarterNote, normalSustainLength},
{(int)493.88, dottedEighthNote, normalSustainLength},
{(int)440.00, sixteenthNote, normalSustainLength},
{(int)493.88, quarterNote, normalSustainLength},
{(int)329.63, eighthNote, normalSustainLength},
{(int)329.63, eighthNote, normalSustainLength},
{(int)440.00, quarterNote, normalSustainLength},
{(int)392, dottedEighthNote, normalSustainLength},
{(int)349.23, sixteenthNote, normalSustainLength},
{(int)392, quarterNote, normalSustainLength},
{(int)261.63, dottedEighthNote, normalSustainLength},
{(int)261.63, sixteenthNote, normalSustainLength},
{(int)523.25, quarterNote, normalSustainLength},
{(int)493.88, dottedEighthNote, normalSustainLength},
{(int)440.00, sixteenthNote, normalSustainLength},
{(int)392.00, halfNote, normalSustainLength * .5},
};
size_t songLength = (sizeof(song) / sizeof(Note));
void playSong(){
for(size_t pos = 0; pos < songLength; ++pos){
const Note& bruh = song[pos];
beep(bruh);
}
}
void setup() {
const int BUZZER_PIN = 8;
pinMode(BUZZER_PIN, OUTPUT);
pinMode(BUTTON_PIN, BUTTON_PINMODE);
playSong();
}
Button button(BUTTON_PIN);
void loop() {
button.waitForPress(LOW);
// read the state of the switch into a local variable:
playSong();
}

Heavy Coin

Oct 4, 2023AustinLeath

0 likes • 3 views

#include <stdio.h>
#include <stdlib.h>
// give an array of identical coins (ints), represented by 1's and one 2
// we can find the heavy coin (2) by summing the contents of the thirds
int sum_subarr(int arr[], int l, int r){
int sum = 0;
for(int i = l; i <= r; i++)
{
sum += arr[i];
}
return sum;
}
int heavy_coin(int arr[], int l, int r){
if(r == l)
{
return r;
}
int midl = l + (r - l)/3;
int midr = r - (r - l)/3;
int lw = sum_subarr(arr, l, midl);
int mw = sum_subarr(arr, midl + 1, midr);
if ( lw > mw )
{
return heavy_coin(arr, l, midl);
}
else if ( lw < mw )
{
return heavy_coin(arr, midl + 1, midr);
}
else
{
return heavy_coin(arr, midr + 1, r);
}
}
int main(int argc, char *argv[])
{
int arr[] = {1,1,1,1,2,1,1,1,1};
int l = 0;
int r = 8;
int res = -1;
res = heavy_coin(arr, l, r);
printf("Hevy coin is at index: %d\n", res);
return EXIT_SUCCESS;
}