c++ - Does Qt have a way of converting bytes to int and vice versa? -


i'm trying find qt function can convert bytes int same endianness i'm using below. feel i'm reinventing wheel here, , there must in qt libs already. exist?

// todo: qt must have built in way of converting bytes int. int ipcreader::bytestoint(const char *buffer, int size) { if (size == 2) { return (((unsigned char)buffer[0]) << 8) + (unsigned char)buffer[1]; } else if (size == 4) { return (((unsigned char)buffer[0]) << 24) + (((unsigned char)buffer[1]) << 16) + (((unsigned char)buffer[2]) << 8) + (unsigned char)buffer[3]; } else { // todo: other sizes, if needed. return 0; } } // todo: qt must have built in way of converting int bytes. void ipcclient::inttobytes(int value, char *buffer, int size) { if (size == 2) { buffer[0] = (value >> 8) & 0xff; buffer[1] = value & 0xff; } else { // todo: other sizes, if needed. } } 

edit: data always big endian (no matter os), example 101 [0, 0, 0, 101] , 78000 [0, 1, 48, 176].

your code pretty simple , easy follow use qt's qbytearray (note: didn't try compiling this):

int ipcreader::bytestoint(const char *buffer, int size) { qbytearray b(buffer, size); return b.toint(); } void ipcclient::inttobytes(int value, char *buffer, int size) { qbytearray b = qbytearray::number(value); strncpy(buffer, (const char*)b, size); } 

note endianness going same machine run on.


Comments

Popular posts from this blog

javascript - backbone.js Collection.add() doesn't `construct` (`initialize`) an object -

php - Get uncommon values from two or more arrays -

Adding duplicate array rows in Php -