I coded stuff for an embedded device where int is 24bits. I wanted to port uint24_t and int24_t to windows, so I made a header file to handle it.
The goal was to have uint24_t and int24_t work as it did when I coded for the embedded device, and for it to be 3 bytes long and unpadded.
My current implementation uses 3 bytes to store a 24bit integer, then converts it to a 32bit integer for math operations. I also handled the special bit-wise not case.
Is there anything I could add or change in the int24_type.h file to improve its preformance?
#include <stdio.h>
#include <stdint.h>
#include "int24_type.h"
int main() { //Example usage
int24_t a = 3;
uint24_t b = 5;
int24_t c = a - b;
int32_t d = -a + b;
c.print_int24_t(); // Printed -2 | FF FF FE
printf("\n%d",d); // Printed 2
return 0;
}
#ifndef INT24_TYPE_H
#define INT24_TYPE_H
class uint24_t {
private:
//Stored across 3 bytes
uint8_t b0;
uint8_t b1;
uint8_t b2;
//Conversions
uint24_t format24(uint32_t i) { //32bit to 24bit
uint24_t z;
z.b0 = i & 255;
z.b1 = (i >> 8) & 255;
z.b2 = (i >> 16) & 255;
return z;
}
uint32_t format32(uint24_t z) { //24bit to 32bit
return (z.b0) | (z.b1 << 8) | (z.b2 << 16);
}
public:
//Constructors
uint24_t() {}
uint24_t(uint32_t i) {
b0 = i & 255;
b1 = (i >> 8) & 255;
b2 = (i >> 16) & 255;
}
operator uint32_t () {
return (b0) | (b1 << 8) | (b2 << 16);
}
//Bitwise NOT
uint24_t operator~() {
uint32_t z = (b0) | (b1 << 8) | (b2 << 16);
return format24(~z);
}
//Debug
void print_uint24_t() {
uint32_t w = (b0) | (b1 << 8) | (b2 << 16);
printf("\n%d | %02X,%02X,%02X",w,b2,b1,b0);
}
};
class int24_t {
private:
//Stored across 3 bytes
uint8_t b0;
uint8_t b1;
uint8_t b2;
//Conversions
int24_t format24(int32_t i) { //32bit to 24bit
int24_t z;
z.b0 = (uint32_t)(i) & 255;
z.b1 = ((uint32_t)(i) >> 8) & 255;
z.b2 = ((uint32_t)(i) >> 16) & 255;
return z;
}
int32_t format32(int24_t z) { //24bit to 32bit
int32_t w = (z.b0) | (z.b1 << 8) | (z.b2 << 16);
if (b2 & 128) { //If bit 23 is set
w |= 0xFF000000;
}
return w;
}
public:
//Constructors
int24_t() {}
int24_t(int32_t i) {
b0 = (uint32_t)(i) & 255;
b1 = ((uint32_t)(i) >> 8) & 255;
b2 = ((uint32_t)(i) >> 16) & 255;
}
operator int32_t () {
int32_t w = (b0) | (b1 << 8) | (b2 << 16);
if (b2 & 128) { //If bit 23 is set
w |= 0xFF000000;
}
return w;
}
//Bitwise Not
int24_t operator~() {
int32_t z = (b0) | (b1 << 8) | (b2 << 16);
return format24(~z);
}
//Debug
void print_int24_t() {
int32_t w = (b0) | (b1 << 8) | (b2 << 16);
if (b2 & 128) { //If bit 23 is set
w |= 0xFF000000;
}
printf("\n%d | %02X,%02X,%02X",w,b2,b1,b0);
}
void print_uint24_t() {
uint32_t w = (b0) | (b1 << 8) | (b2 << 16);
printf("\n%d | %02X,%02X,%02X",w,b2,b1,b0);
}
};
#endif /* INT24_TYPE_H */
uint_least24_twith a serialize/deserialize that handles endian-ness properly? Then you can just use native types on both platforms, and exchange data safely. \$\endgroup\$