forked from vedderb/bldc-logger
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utility.cpp
91 lines (75 loc) · 2.65 KB
/
utility.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/*
* buffer.c
*
* Created on: 13 maj 2013
* Author: benjamin
*/
#include "utility.h"
#include <cmath>
namespace {
inline double roundDouble(double x) {
return x < 0.0 ? ceil(x - 0.5) : floor(x + 0.5);
}
}
namespace utility {
void buffer_append_int32(uint8_t* buffer, int32_t number, int32_t *index) {
buffer[(*index)++] = number >> 24;
buffer[(*index)++] = number >> 16;
buffer[(*index)++] = number >> 8;
buffer[(*index)++] = number;
}
void buffer_append_uint32(uint8_t* buffer, uint32_t number, int32_t *index) {
buffer[(*index)++] = number >> 24;
buffer[(*index)++] = number >> 16;
buffer[(*index)++] = number >> 8;
buffer[(*index)++] = number;
}
void buffer_append_int16(uint8_t* buffer, int16_t number, int32_t *index) {
buffer[(*index)++] = number >> 8;
buffer[(*index)++] = number;
}
void buffer_append_uint16(uint8_t* buffer, uint16_t number, int32_t *index) {
buffer[(*index)++] = number >> 8;
buffer[(*index)++] = number;
}
void buffer_append_double16(uint8_t* buffer, double number, double scale, int32_t *index) {
buffer_append_int16(buffer, (int16_t)(roundDouble(number * scale)), index);
}
void buffer_append_double32(uint8_t* buffer, double number, double scale, int32_t *index) {
buffer_append_int32(buffer, (int32_t)(roundDouble(number * scale)), index);
}
int16_t buffer_get_int16(const uint8_t *buffer, int32_t *index) {
int16_t res = ((uint8_t) buffer[*index]) << 8 |
((uint8_t) buffer[*index + 1]);
*index += 2;
return res;
}
uint16_t buffer_get_uint16(const uint8_t *buffer, int32_t *index) {
uint16_t res = ((uint8_t) buffer[*index]) << 8 |
((uint8_t) buffer[*index + 1]);
*index += 2;
return res;
}
int32_t buffer_get_int32(const uint8_t *buffer, int32_t *index) {
int32_t res = ((uint8_t) buffer[*index]) << 24 |
((uint8_t) buffer[*index + 1]) << 16 |
((uint8_t) buffer[*index + 2]) << 8 |
((uint8_t) buffer[*index + 3]);
*index += 4;
return res;
}
uint32_t buffer_get_uint32(const uint8_t *buffer, int32_t *index) {
uint32_t res = ((uint8_t) buffer[*index]) << 24 |
((uint8_t) buffer[*index + 1]) << 16 |
((uint8_t) buffer[*index + 2]) << 8 |
((uint8_t) buffer[*index + 3]);
*index += 4;
return res;
}
double buffer_get_double16(const uint8_t *buffer, double scale, int32_t *index) {
return (double)buffer_get_int16(buffer, index) / scale;
}
double buffer_get_double32(const uint8_t *buffer, double scale, int32_t *index) {
return (double)buffer_get_int32(buffer, index) / scale;
}
}