d2stat.c
1.91 KB
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
#include "d2stat.h"
#include <stdio.h>
#include <string.h>
#define readBits(data, start, size) ((*((uint64_t*) &data[(start) / 8]) >> ((start) & 7)) & ((1 << (size)) - 1))
// Internal function, gives the offset ***IN BITS, NOT BYTES*** of the specified stat
unsigned long long int _searchStat(D2S_STAT stat, void* charData, size_t dataLen) {
if(!strncmp(charData, D2S_STAT_HEADER, D2S_STAT_HEADER_LENGTH)) {
fprintf(stderr,"libd2char error: Stat header not present in charData\n");
return 0;
}
unsigned long long int offset = D2S_STAT_HEADER_LENGTH * 8;
while(offset < (dataLen * 8)) {
uint64_t statID = readBits(charData, offset, D2S_STAT_IDENTIFIER_BIT_LENGTH);
if(statID == D2S_STAT_FOOTER) {
break;
} else if(statID == stat) {
return offset + D2S_STAT_IDENTIFIER_BIT_LENGTH;
}
offset += D2S_STAT_IDENTIFIER_BIT_LENGTH + statCost[statID];
}
return 0;
}
int getStat(D2S_STAT stat, unsigned int* value, void* charData, size_t dataLen) {
unsigned long long int statOffset = _searchStat(stat,charData,dataLen);
if(!statOffset) {
fprintf(stderr,"libd2char error: Unable to find attribute: %d\n", stat);
return -1;
}
uint64_t statValue = readBits(charData, statOffset, statCost[stat]);
*value = (unsigned int)statValue;
return 0;
}
int setStat(D2S_STAT stat, unsigned int value, void* charData, size_t dataLen) {
unsigned long long int statOffset = _searchStat(stat,charData,dataLen);
if(!statOffset) {
fprintf(stderr,"libd2char error: Unable to find attribute: %d\n", stat);
return -1;
}
uint64_t statValue = 0;
memcpy(&statValue, charData + (statOffset / 8), sizeof(statValue));
statValue &= (~statCostMask[stat] << (statOffset % 8));
statValue |= (value << (statOffset % 8));
memcpy(charData + (statOffset / 8), &statValue, sizeof(statValue));
return 0;
}