varbyterw.c (2260B)
1 /* 2 Variable-Byte Reader/Writer implemetation file 3 varbyterw.c 4 M. Yamanaka 5 email: myamanaka@live.com 6 website: csmyamanaka.com 7 license: MIT (See included "LICENSE" file for details) 8 */ 9 10 #include "varbyterw.h" 11 12 13 int wDataToChar(void* ipt, char* dst, int b, int e){ 14 /* 15 ipt ... input data 16 dst ... destination array 17 b ... number of bytes 18 e ... endian-ness. 0 indicates little-endian and 1, big-endian 19 */ 20 21 /* 22 I could be wrong but I'm pretty sure gcc (or at least the version that I'm using) stores variables as little-endian 23 I came to this conclusion because I tested out the following code: 24 25 int main(){ 26 int n = 65; 27 int* pn = &n; 28 char* pcn = (char*)pn; 29 if(*pcn == '\0' && *(pcn + 3) == 'A') printf("big endian\n"); 30 else if(*pcn == 'A' && *(pcn + 3) == '\0') printf("little endian\n"); 31 else printf("something probably went wrong\n"); 32 return 0; 33 } 34 35 and got the second print statement. 36 I don't know if this varies from compiler to compiler. 37 If it helps, I tested this on Void Linux using GCC 9.3.0 38 */ 39 40 /* 41 Assuming that the variables are indeed stored in little-endian format, 42 if match the indices as the bytes are being written, 43 the resulting byte array should also be little-endian. 44 If one of the indices is reversed, the result should be big-endian. 45 46 The for-loop below may look a little convoluted but it should handle both cases: 47 i.e. when e = 0, thereby making (e != 0) = 0, i and j should match 48 whereas i would count up from 0 to b - 1 and j would count down 49 from b - 1 to 0 when e = 1 since it would make (e != 0) = 1. 50 It saves me from having to write two for loops or an if statement in the loop 51 thereby making the code shorter suckless style 52 */ 53 54 for(int i = 0, j = (b - 1)*(e != 0); i < b; i++, j += 1 - 2*(e != 0)) dst[i] = *((char*)ipt + j); 55 56 return 0; 57 } 58 59 int rDataFromChar(char* ipt, void* dst, int b, int e){ 60 /* 61 ipt ... input array 62 dst ... destination data 63 b ... number of bytes to interpret 64 e ... endian-ness, 0 for little-endian and 1 for big-endian 65 */ 66 67 for(int i = 0, j = (b - 1)*(e != 0); i < b; i++, j += 1 - 2*(e != 0)) *((char*)dst + i) = ipt[j]; 68 return 0; 69 } 70