Skip to content

Instantly share code, notes, and snippets.

@GuilhermeRossato
Created April 17, 2020 05:31
Show Gist options
  • Save GuilhermeRossato/e9f1eaa705f6fb45db339f6078da7b14 to your computer and use it in GitHub Desktop.
Save GuilhermeRossato/e9f1eaa705f6fb45db339f6078da7b14 to your computer and use it in GitHub Desktop.
2d uint8 tensor implementation in C

2D Uint8 Tensor in C

A simple structure to hold 2d uint8 arrays in C that can be easily adjusted to hold other things in other dimensions.

Usage is as follows:

struct uint8_tensor * t = create_tensor(2, 2);
t->set(t, 0, 0, 0);
t->set(t, 0, 1, 1);
t->set(t, 1, 0, 1);
t->set(t, 1, 1, 0);
// t->data == {0, 1, 1, 0}
destroy_tensor(t); // Don't forget to deallocate to avoid memory leaks!
#pragma once
#include <stdint.h>
struct uint8_tensor {
uint8_t * data;
int width;
int height;
uint8_t (*get)(struct uint8_tensor * t, int x, int y);
uint8_t (*set)(struct uint8_tensor * t, int x, int y, uint8_t value);
};
uint8_t tensor_get(struct uint8_tensor * t, int x, int y) {
if (x < 0 || x >= t->width || y < 0 || y >= t->height) {
return 0;
}
return t->data[x + y * t->width];
}
uint8_t tensor_set(struct uint8_tensor * t, int x, int y, uint8_t v) {
if (x < 0 || x >= t->width || y < 0 || y >= t->height) {
return 0;
}
return t->data[x + y * t->width] = v;
}
struct uint8_tensor * create_tensor(int width, int height) {
struct uint8_tensor * t = malloc(sizeof(struct uint8_tensor));
t->data = malloc(sizeof(uint8_t) * width * height);
t->width = width;
t->height = height;
t->get = tensor_get;
t->set = tensor_set;
}
void destroy_tensor(struct uint8_tensor * t) {
free(t->data);
free(t);
}
#pragma once
#include <stdint.h>
struct ubyte_tensor;
struct ubyte_tensor * create_tensor(int width, int height);
void destroy_tensor(struct ubyte_tensor * t);
uint8_t tensor_get(struct ubyte_tensor * t, int x, int y);
uint8_t tensor_set(struct ubyte_tensor * t, int x, int y, uint8_t v);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment