Mopparthy Ravindranath
Mopparthy Ravindranath

Reputation: 3308

Redis how to store a number instead of string

I am trying to store a number as a value in Redis key. For example, I want to store a value of 4. and I don't want it to be stored as "4". Why I need this? Because when I retrieve this value back, I will be doing some bitwise op on it. If it stores as "4" (instead of 4), the value actually stored in Redis seems to be 52 (that is... 00110100 instead of 00000100).

You might wonder, why I don't use Redis bitops. The reason is I have to store an array of many bits. I don't want to be doing redis bitops in a loop. I just want to locally create an equivalent array and upload it by calling set command.

In Javascript, I tried doing

redis.set(key, 4)

obviously it didn't work. Then I tried

redis.set(key, "\x04")

This works. But how do I store an array of bytes by converting to this format? What am I missing here?

Upvotes: 5

Views: 8729

Answers (1)

advance512
advance512

Reputation: 1358

Internally, if all of the values of a data type are numeric, then the data is stored by its numeric representation. Otherwise, the data is stored as a string. You cannot force Redis to use a specific representation method for a single data point, as far as I know, and anyways - you'll always get the value as a string. You'll need to parse the value yourself and convert it into an integer, float, etc.

Upvotes: 7

Related Questions