Am I XOR'ing efficiently here?

Hi,

I am reading 9 bytes from a file that have been XOR’ed with FF

Is there a better way to do this?

      room_name = IO.binread(assets_file_pointer, 9)
      |> :binary.decode_unsigned
      |> Bitwise.bxor(0xFFFFFFFFFFFFFFFFFF)
      |> :binary.encode_unsigned

Thanks…

I would probably do it byte by byte instead:

room_name =
  assets_file_pointer
  |> IO.binread(9)
  |> xor_with(0xFF)

# …

def xor_with(binary, byte) when is_binary(binary) and byte in 0..255 do
  for <<b <- binary>>, into: <<>>, do: Bitwise.xor(b, byte)
end
1 Like

Ah ok - thanks heaps… didn’t know you could do that.

@hauleth For that to work, I need to wrap the Bitwise.xor in angled brackets (otherwise erlang gave an argument error), still not quite sure why I needed to that. But anyway, thanks again… Updated to:

def xor_with(binary, byte) when is_binary(binary) and byte in 0..255 do
  for <<b <- binary>>, into: <<>>, do: <<Bitwise.xor(b, byte)>>
end
1 Like