Skip to main content

3 posts tagged with "C#"

View all tags

Function to return MD5 (string) from string (C#)

· One min read

Functions used

  • byte[] Encoding.UTF8.GetBytes(string) Converts a string to a byte[]
  • MD5 MD5.Create() Creates an MD5 instance
  • byte[] md5.ComputeHash(byte[]) Generates an MD5 hash from a byte[]

Example

string str2MD5(string src)
{
byte[] srcBytes = Encoding.UTF8.GetBytes(src);
string MD5src;
using (MD5 md5 = MD5.Create())
{
byte[] MD5srcBytes = md5.ComputeHash(srcBytes);
StringBuilder sb = new();
for (int i = 0; i < MD5srcBytes.Length; i++)
sb.Append(MD5srcBytes[i].ToString("x2"));
MD5src = sb.ToString();
}
return MD5src;
}

Handling 2D arrays in C

· One min read

It is convenient to manage memory where numbers are stored by summarizing the number of rows, number of columns, and the memory itself in a structure.

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

typedef struct {
float *data;
int col_size;
int row_size;
} Mat;

void MatInit(Mat *mat, int row_size, int col_size) {
mat->row_size = row_size;
mat->col_size = col_size;
mat->data = (float *)calloc(row_size * col_size, sizeof(float));
}

float *MatAt(Mat *mat, int i, int j) {
return mat->data + i * mat->col_size + j;
}

void MatFree(Mat *mat) { free(mat->data); }

int main(void) {
Mat mat;
MatInit(&mat, 30, 5); // Initialize a matrix with 30 rows and 5 columns
*MatAt(&mat, 0, 0) = 50; // Assign 50 to row 0, column 0
printf("%f\n", *MatAt(&mat, 0, 0)); // Print the value at row 0, column 0

MatFree(&mat);

return 0;
}
Tags:

Creating a DLL and compiling with C

· One min read

Notes on creating a DLL and compiling C

Library

Source file

// gcd.c
int gcd(int a, int b){
return !b ? a : gcd(b, a % b);
}

Header file

// gcd.h
#ifndef TEST_H
#define TEST_H

int gcd(int a, int b);

#endif

Program

#include <stdio.h>
#include "gcd.h"

int main(void){
printf("%d\n", gcd(24, 36));
}

Compilation

Creating the DLL

gcc gcd.c -shared -o gcd.dll

Compile

gcc main.c -lgcd -L.