Skip to main content

Fast inverse square root

0 likes • Nov 19, 2022 • 0 views
C
Loading...

More C Posts

execlp() example

0 likes • Nov 19, 2022 • 0 views
C
#include <stdio.h>
#include <unistd.h>
int main() {
char * cmd[] = {
"who",
"ls",
"date"
};
int i;
printf("0=who 1=ls 2=date : ");
scanf("%d", & i);
execlp(cmd[i], cmd[i], (char * ) 0);
printf("execlp failed\n");
return 0;
}

replaceString

0 likes • Nov 14, 2021 • 0 views
C
//===============replaceString.c===============
#include "replaceString.h"
//Normally I'd make a replaceStringMalloc to return a malloced string or a replaceStringMut to change the original string, but I'm not satisfied with those function names so it's best just to do to = (char*)malloc(replaceStringLength(from, replace, replacement)); replaceString(to, from, replace, replacement);
//If this was c++, I'd have no problem just overloading replaceString
//Returns the length of the resulting string (minus the null char)
size_t replaceStringLength(const char* from, const char* replace, const char* replacement){
size_t fromLength = strlen(from);
size_t replaceLength = strlen(replace);
size_t replacementLength = strlen(replacement);
size_t fromEndIt = 0;
size_t toLength = 0;
while(fromEndIt < fromLength){
int replaceIt = 0;
while(replaceIt < replaceLength && (fromEndIt+replaceIt) < fromLength && from[fromEndIt + replaceIt] == replace[replaceIt]){
++replaceIt;
}
if(replaceIt == replaceLength){
//Update from buffer iterator positions
toLength += (fromEndIt + replacementLength);
from += (fromEndIt + replaceLength);
fromEndIt = 0;
continue;
}
++fromEndIt;
}
toLength += fromEndIt;
return toLength;
}
//Baller replaceString by Leif Messinger
//Needs null terminated from, replace, and replacement strings as well as a large block of memory to store the result.
void replaceString(char* to, const char* from, const char* replace, const char* replacement){
size_t fromLength = strlen(from);
size_t replaceLength = strlen(replace);
size_t replacementLength = strlen(replacement);
size_t fromEndIt = 0;
while(fromEndIt < fromLength){
int replaceIt = 0;
while(replaceIt < replaceLength && (fromEndIt+replaceIt) < fromLength && from[fromEndIt + replaceIt] == replace[replaceIt]){
++replaceIt;
}
if(replaceIt == replaceLength){
//Copy the string before the matched bit
memcpyToAndShiftPointers(to, from, fromEndIt);
//Copy the replacement too
memcpyToAndShiftPointer(to, replacement, replacementLength);
//Update from buffer iterator positions
from += replaceLength;
fromEndIt = 0;
continue; //I don't want this thing to get incremented again
}
++fromEndIt;
}
//Copy the rest of the unmatched string
memcpyToAndShiftPointer(to, from, fromEndIt);
to[0] = '\0'; //Should work
}
//===============replaceString.h===============
#ifndef REPLACE_STRING_H
#define REPLACE_STRING_H
#include <string.h>
#define memcpyToAndShiftPointer(to,from,n); memcpy((to),(from),(n)); (to) += (n);
#define memcpyToAndShiftPointers(to,from,n); memcpy((to),(from),(n)); (to) += (n); (from) += n;
//Normally I'd make a replaceStringMalloc to return a malloced string or a replaceStringMut to change the original string, but I'm not satisfied with those function names so it's best just to do to = (char*)malloc(replaceStringLength(from, replace, replacement)); replaceString(to, from, replace, replacement);
//If this was c++, I'd have no problem just overloading replaceString
//Returns the length of the resulting string (minus the null char)
size_t replaceStringLength(const char* from, const char* replace, const char* replacement);
//Baller replaceString by Leif Messinger
//Needs null terminated from, replace, and replacement strings as well as a large block of memory to store the result.
void replaceString(char* to, const char* from, const char* replace, const char* replacement);
#endif
//===============replaceStringMain.c===============
#include <stdio.h>
#include <stdlib.h>
#include "replaceString.h"
#define BUFFER_SIZE (1<<21) //About a mebibyte
//There could be matches between buffers, so make sure the buffer size you set it to is good enough for your application. Basically as big as your input.
//Replaces strings from sdtin, then outputs it to stdout
//./a.out [[replace], [replacement]]...
int main(int argc, char** argv){
char* buffer1 = (char*) malloc(BUFFER_SIZE);
char* buffer2 = (char*) malloc(BUFFER_SIZE);
if(buffer1 == NULL || buffer2 == NULL){
perror("You need a couple MBs of ram my boy");
return 1;
}
while(!feof(stdin)){
fread(buffer1, BUFFER_SIZE, 1, stdin);
char* activeBuffer = buffer1;
char* inactiveBuffer = buffer2;
char* tmp;
for(size_t i = 1; (i + 1) < argc; i += 2){
//puts(activeBuffer);
replaceString(inactiveBuffer, activeBuffer, argv[i], argv[i+1]);
//Swap buffers
tmp = activeBuffer;
activeBuffer = inactiveBuffer;
inactiveBuffer = tmp;
}
fputs(activeBuffer, stdout);
}
free(buffer1);
free(buffer2);
return 0;
}

Heavy Coin

0 likes • Oct 4, 2023 • 2 views
C
#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;
}

socketUDPPingServer.c

0 likes • Aug 5, 2023 • 2 views
C
// Server 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 RECIEVE_BUFFER_SIZE 1024
// Driver code
int main() {
//Create a UDP socket
//int socket(int domain, int type, int protocol);
//Domain is the place where the data goes. AF_BLUETOOTH, AF_INET6, AF_UNIX is local communication between different programs
//Type is the type of connection, so connection based (TCP), connectionless (UDP) or somewhere in between or beyond
//Protocol is an enum or flags that give some more options specific to that type. For SOCK_STREAM, you can force it to use SCTP instead of TCP. For SOCK_RAW, it can give you control over the ip frame, and even the ethernet frame.
//So this function makes a file descriptor to an IPV4 UDP 'connection' with no options.
int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
// Creating socket file descriptor
if ( sockfd < 0) {
perror("socket creation failed");
exit(EXIT_FAILURE);
}
struct sockaddr_in serverAddress;
memset(&serverAddress, 0, sizeof(serverAddress));
// Filling server information
serverAddress.sin_family = AF_INET; // IPv4
serverAddress.sin_addr.s_addr = INADDR_ANY;
serverAddress.sin_port = htons(PORT);
// Bind the socket with the server address
if(bind(sockfd, (const struct sockaddr*)&serverAddress, sizeof(serverAddress))){ //Bind returns 0 if succeeded, or -1 if failed. -1 is still true.
perror("bind failed");
exit(EXIT_FAILURE);
}
struct sockaddr_in clientAddress; unsigned int clientAddressSize = sizeof(clientAddress);
memset(&clientAddress, 0, clientAddressSize);
char buffer[RECIEVE_BUFFER_SIZE];
while(1){
int bytesRecieved = recvfrom(sockfd, (char*)buffer, RECIEVE_BUFFER_SIZE, MSG_WAITALL, (struct sockaddr*) &clientAddress, &clientAddressSize); //sets clientAddress to the client's address and the new size
buffer[bytesRecieved] = '\0';
//printf("Client : %s\n", buffer);
//The client might be like PINGUIN or something, but this is to ensure PING\n\r also gets accepted
if(bytesRecieved >= 4 && (strncmp("PING", buffer, 4) == 0)){
const char* responseMessage = "PONG";
sendto(sockfd, (const char*)responseMessage, strlen(responseMessage), MSG_CONFIRM, (const struct sockaddr*) &clientAddress, clientAddressSize);
//printf("Hello message sent.\n");
}else{
printf("Server bytes recieved: %d\nServer message recieved: %s", bytesRecieved, buffer);
}
}
return 0;
}

wait() example

0 likes • Nov 19, 2022 • 0 views
C
#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 */

Bitwise operators with pointers

0 likes • Nov 18, 2022 • 0 views
C
#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);
}