Skip to content

Instantly share code, notes, and snippets.

@EasyIP2023
Last active March 3, 2020 00:24
Show Gist options
  • Select an option

  • Save EasyIP2023/910be82dab9da458b772ce6f09ae3ccd to your computer and use it in GitHub Desktop.

Select an option

Save EasyIP2023/910be82dab9da458b772ce6f09ae3ccd to your computer and use it in GitHub Desktop.
Uselful methods

Useful methods

Just an md file full of methods that one could potentially use in the future

C

Lower case letters to upper

void lower_to_upper(char *s) {
  while (*s != '\0') {
    if (*s >= 'a' && *s <= 'z')
      *s = ('A' + *s - 'a');
    s++;
  }
}

Replace white spaces

void replace_white_spaces(char *s) {
  while (*s != '\0') {
    if (*s == ' ')
      *s = '0';
    s++;
  }
}

Get power

long int get_pow(int x, int n) {
  int result = 1;

  while (n != 0) {
    result *= x;
    --n;
  }

  return result;
}

Hexidecimal to decimal

int hex_to_dec(char *hex) {
  int dec=0, i=strlen(hex), p=0, j;

  for (j = i-1; j >= 0; j--) {
    if (hex[j] > 57)
      dec += (hex[j] - 55) * get_pow(16, p);
    else
      dec += (hex[j] - 48) * get_pow(16, p);
    p++;
  }

  return dec;
}

String Concat with variable length size

#include <stdarg.h>
#include <assert.h>

char *concat(char *fmt, ...) {
  char *result = NULL;
  size_t size = 0;
  va_list args; /* type that holds variable arguments */

  /* Determine required size */
  va_start(args, fmt);
  size = vsnprintf(result,size,fmt,args);
  va_end(args);
  assert(size > 0);

  size++; /* for '/0' sentinal character */
  result = calloc(sizeof(result), size);
  assert(result != NULL);

  va_start(args, fmt);
  size = vsnprintf(result,size,fmt,args);
  va_end(args);

  // This disables compiler warnings
  if (!(size > 0)) {
    free(result);
    return NULL;
  }

  return result;
}
int main() {
  char *result = concat("%s - %s\n", "testing", "teste");
  char *s2 = concat("%s : %d\n", "testing", 50);

  printf("%p : %s",result, result);
  printf("%s", s2);
  
  free(result);
  free(s2);
  return 0;
}

Redirect stdout to a file

/* https://www.unix.com/programming/268879-c-unix-how-redirect-stdout-file-c-code.html */
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>

int main(int argc, const char *argv[])
{
    int out = open("cout.log", O_RDWR|O_CREAT|O_APPEND, 0600);
    if (-1 == out) { perror("opening cout.log"); return 255; }

    int err = open("cerr.log", O_RDWR|O_CREAT|O_APPEND, 0600);
    if (-1 == err) { perror("opening cerr.log"); return 255; }

    int save_out = dup(fileno(stdout));
    int save_err = dup(fileno(stderr));

    if (-1 == dup2(out, fileno(stdout))) { perror("cannot redirect stdout"); return 255; }
    if (-1 == dup2(err, fileno(stderr))) { perror("cannot redirect stderr"); return 255; }

    puts("doing an ls or something now");

    fflush(stdout); close(out);
    fflush(stderr); close(err);

    dup2(save_out, fileno(stdout));
    dup2(save_err, fileno(stderr));

    close(save_out);
    close(save_err);

    puts("back to normal output");

    return 0;
}

Redirect stdout to a file via pass by reference

void redirect_stdout(char *filename, int *out, int *save_out) {
  *out = open(filename, O_RDWR|O_CREAT|O_APPEND, 0600);
  if (*out == -1) { fprintf(stderr, "[x] failed to open %s\n", filename); return; }

  *save_out = fcntl(fileno(stdout), F_DUPFD, 0);
  if (*save_out == -1) { fprintf(stderr, "[x] Cannot open output file\n"); return; }

  if (dup2(*out, fileno(stdout)) == -1) {
    fprintf(stderr, "[x] Cannot redirect stdout\n");
    return;
  }
}

void reset_stdout(int *out, int *save_out) {
  fflush(stdout);
  close(*out);
  if (dup2(*save_out, fileno(stdout)) == -1) {
    fprintf(stderr, "[x] Cannot redirect stdout\n");
    return;
  }
  close(*save_out);
}

Unused function variables

/* http://efesx.com/2010/07/17/variadic-macro-to-count-number-of-arguments/ */
/* https://stackoverflow.com/questions/23235910/variadic-unused-function-macro */
#define UNUSED1(z) (void)(z)
#define UNUSED2(y,z) UNUSED1(y),UNUSED1(z)
#define UNUSED3(x,y,z) UNUSED1(x),UNUSED2(y,z)
#define UNUSED4(b,x,y,z) UNUSED2(b,x),UNUSED2(y,z)
#define UNUSED5(a,b,x,y,z) UNUSED2(a,b),UNUSED3(x,y,z)

#define VA_NUM_ARGS_IMPL(_1,_2,_3,_4,_5, N,...) N
#define VA_NUM_ARGS(...) VA_NUM_ARGS_IMPL(__VA_ARGS__, 5, 4, 3, 2, 1)

#define ALL_UNUSED_IMPL_(nargs) UNUSED ## nargs
#define ALL_UNUSED_IMPL(nargs) ALL_UNUSED_IMPL_(nargs)
#define ALL_UNUSED(...) ALL_UNUSED_IMPL( VA_NUM_ARGS(__VA_ARGS__))(__VA_ARGS__ )

Min & Max Macros

#define max(a,b) \
   ({ __typeof__ (a) _a = (a); \
       __typeof__ (b) _b = (b); \
     _a > _b ? _a : _b; })

#define min(a,b) \
  ({ __typeof__ (a) _a = (a); \
      __typeof__ (b) _b = (b); \
    _a < _b ? _a : _b; })

Integer to binary macro

#define INT_TO_BIN(n) \
	do { \
		(n & 1) ? printf("1") : printf("0"); \
		n >>= 1; \
	} while(n > 0)

Is a power of 2

// 8 0000 1000 -> Is a power of 2
// 7 0000 0111
// & 0000 0000
//
// 7 0000 0111 -> Not a power of 2
// 6 0000 0110
// & 0000 0110
//
// 4 0000 0100 -> Is a power of 2
// 3 0000 0011
// & 0000 0000

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

bool is_power_two(int num) {
	return num > 0 && !(num & (num - 1));
}

int main(void) {
	for (int i = 0; i < 33; i++)
		fprintf(stdout, "num %d: %d\n", i, is_power_two(i));
	return 0;
}

Reverse Buffer in place

void reverse_buffer(char *buffer, int len) {
	char temp;
	int j = 0;
	for (int i = len; i >= j; i--) {
		temp = buffer[j];
		buffer[j] = buffer[i];
		buffer[i] = temp;
	}
}

Pad hex chars out

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main () {
	char *addr = "0x1";
	
	char pad[19];
	memset(pad, 0, sizeof(pad));

	char *temp = addr + strlen(addr) - 1;

	char temp_buff[4];
	memset(temp_buff, 0, sizeof(temp_buff));

	int i = 0;
	while (*temp != 'x') {
		temp_buff[i++] = *temp;
		temp--;
	}
	
	pad[0] = addr[0];
	pad[1] = addr[1];

	int j = 2;
	for (; j < sizeof(pad) - i; j++) pad[j] = '0';

	i = 0;
	for (int x = j; x < sizeof(pad); x++) pad[x] = temp_buff[i++];

	pad[19] = '\0';

	return 0;
}

Ruby

Finding Prime Numbers

# https://stackoverflow.com/questions/30437606/ruby-method-for-generating-prime-numbers
@primes = []
def prime_numbers(n)
  i = 2
  while @primes.size < n do
    @primes << i if is_prime?(i)
    i += 1
  end
  @primes
end

def is_prime?(n)
  @primes.each { |prime| return false if n % prime == 0 }
  true
end

prime_numbers(3599)

Find inverse

# Find the inverse of a number
n=31
m=(@x-1)*(@y-1)

def inv(n,m)
  max=0
  val=0
  while true
    val = val + 1
    result = (val * n) % m
    break if (result==1)
    return 0 if (max>1500)
  end
  return val
end

puts (m<n) ? "m need to be larger than n" : "The inverse of #{n} mod #{m} is #{inv(n,m)}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment