binary format, bitwise operations exist? eg. <<

2019-04-06 13:27发布

问题:

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

1>  127 bsl 1.
254

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

<< 16#7F, 16#FF >>

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>  << 16#7F, 16#FF >> bsl 1.
<< 255, 254 >>

回答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.