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

ⅰ亾dé卋堺 提交于 2019-12-05 20:44:07

问题


In erlang, there are bitwise operations to operate on integers, for example:

1&gt  127 bsl 1.
254

there is also the ability to pack integers into a sequence of bytes

&lt&lt 16#7F, 16#FF &gt&gt

is it possible, or are there any operators or BIFs that can perform bitwise operations (eg AND, OR, XOR, SHL, SHR) on binary packed data?

for example (if bsl worked on binary packages - which it does not):

1&gt  &lt&lt 16#7F, 16#FF &gt&gt bsl 1.
&lt&lt 255, 254 &gt&gt

回答1:


Try out this way:

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



回答2:


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.



来源:https://stackoverflow.com/questions/390641/binary-format-bitwise-operations-exist-eg-167f-16ff-bsl-1

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