given : int x[3] = {11,22,33}; how can save it as a key's value as binary data and get it
the hiredis give example to how to set binary safestring
/* Set a key using binary safe API */
reply = redisCommand(c,"SET %b %b", "bar", (size_t) 3, "hello", (size_t) 5);
printf("SET (binary API): %s\n", reply->str);
freeReplyObject(reply);
but how about other data and how to get ?
Storing directly binary data in a remote store without any kind of marshalling is a recipe for disaster. I would not recommend to do it: there are plenty of serialization protocols you could use to make binary data independent from the platform.
That said, to answer your question:
// This is the key
int k[3] = {11,22,33};
// This is the value
int v[4] = {0,1,2,3};
redisReply *reply = 0;
// Store the key/value: note the usage of sizeof to get the size of the arrays (in bytes)
reply = redisCommand(context, "SET %b %b", k, (size_t) sizeof(k), v, (size_t) sizeof(v) );
if (!reply)
return REDIS_ERR;
freeReplyObject(reply);
// Now, get the value back, corresponding to the same key
reply = redisCommand(context, "GET %b", k, (size_t) sizeof(k) );
if ( !reply )
return REDIS_ERR;
if ( reply->type != REDIS_REPLY_STRING ) {
printf("ERROR: %s", reply->str);
} else {
// Here, it is safer to make a copy to be sure memory is properly aligned
int *val = (int *) malloc( reply->len );
memcpy( val, reply->str, reply->len);
for (int i=0; i<reply->len/sizeof(int); ++i )
printf("%d\n",val[i]);
free( val );
}
freeReplyObject(reply);
Note that this kind of code only works if you are sure that all your Redis clients run on systems with the same endianness and same sizeof(int).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With