binary format, bitwise operations exist? eg. <<16#7F, 16#FF>> bsl 1

别来无恙 提交于 2019-12-04 03:16:52

Try out this way:

bbsl(Bin,Shift) -> <<_:Shift,Rest/bits>> = Bin, <<Rest/bits,0:Shift>>.

Using Erlang's unbounded integer sizes we can accomplish this:

1> Bits = <<16#0FFFFFFF:(4*8)>>.
<<15,255,255,255>>

2> size(Bits).
4

3> Size=size(Bits)*8.
32

4> <<Num:Size>> = Bits.
<<15,255,255,255>>

5> Num.
268435455

6> Num2 = Num bsl 4.
4294967280

7> Bits2 = <<Num2:Size>>.
<<"ÿÿÿð">>

8> <<A:8,B:8,C:8,D:8>>=Bits2.
<<"ÿÿÿð">>

9> A.
255

10> D.
240

as we expected.

Note that in my solution I anticipated how many shifts I would need (4) by adding 4 '0's to the initial string stored in the binary (16#0F... the first 4 positions are 0)

Not sure how I would handle it if I had to shift beyond the 'boundary' of the binary container, I guess you would just AND with 2^Size-1.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!