redis的setbit命令

來源:互聯網
上載者:User

標籤:osc   table   and   asc   舉例   通過   www   editable   offset   

redis的setbit這個bit怎麼理解,配合bitcount使用?


這個是SETBIT使用方法的簡單說明
<img src="https://pic4.zhimg.com/8650852c348cf08ff711e44ca13aaf47_b.png" data-rawwidth="958" data-rawheight="93" class="origin_image zh-lightbox-thumb" width="958" data-original="https://pic4.zhimg.com/8650852c348cf08ff711e44ca13aaf47_r.png">

在redis中,儲存的字串都是以二級制的進行存在的。

舉例:
設定一個 key-value ,鍵的名字叫“andy” 值為字元‘a‘
<img src="https://pic3.zhimg.com/85f9a07a4cfb815029f4ce266daa78a2_b.png" data-rawwidth="524" data-rawheight="99" class="origin_image zh-lightbox-thumb" width="524" data-original="https://pic3.zhimg.com/85f9a07a4cfb815029f4ce266daa78a2_r.png">
我們知道 ‘a‘ 的ASCII碼是 97。轉換為二進位是:01100001。offset的學名叫做“位移” 。二進位中的每一位就是offset值啦,比如在這裡 offset 0 等於 ‘0’ ,offset 1等於‘1‘ ,offset2等於‘1‘,offset 6 等於‘1‘ ,沒錯,offset是從左往右計數的,也就是從高位往低位。

我們通過SETBIT 命令將 andy中的 ‘a‘ 變成 ‘b‘ 應該怎麼變呢?

也就是將 01100001 變成 01100010 (b的ASCII碼是98),這個很簡單啦,也就是將‘a‘中的offset 6從0變成1,將offset 7 從1變成0 。

<img src="https://pic1.zhimg.com/4a65befc057124bb36c880758b26b7fc_b.png" data-rawwidth="521" data-rawheight="96" class="origin_image zh-lightbox-thumb" width="521" data-original="https://pic1.zhimg.com/4a65befc057124bb36c880758b26b7fc_r.png">
大家可能也發現了,每次SETBIT完畢之後,有一個(integer) 0或者(integer)1的傳回值,這個是在你進行SETBIT 之前,該offset位的位元值。

這個時候,我們再get andy 一下,看看結果:
<img src="https://pic2.zhimg.com/9591d4a73f3471847bbc6ade20d7f94d_b.png" data-rawwidth="340" data-rawheight="50" class="content_image" width="340">
果然,就從‘a‘ 變成 ‘b‘了。 

這就是redis 中 “SETBIT” 的基本用法。

BITCOUNT 就是統計字串的二級制碼中,有多少個‘1‘。 所以在這裡,

BITCOUNT andy 得到的結果就是 3 啦。

以上。 轉自 https://www.zhihu.com/question/27672245/answer/123641959

redis的setbit命令

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.