Convert pointer to loop option in C#
Asked Answered
W

1

1

How would I convert this into a loop and not to use the pointer.

byte[] InputBuffer = new byte[8];
unsafe {
      fixed (byte* pInputBuffer = InputBuffer) {
         ((long*)pInputBuffer)[0] = value;
      }
}

I am trying to use the code from this page: query string parameter obfuscation

Wellmannered answered 3/2, 2011 at 3:26 Comment(0)
M
3

There's no looping here. You could use BitConverter.GetBytes instead of the unsafe type-punning cast.

byte[] InputBuffer = BitConverter.GetBytes(value);

replaces all six original lines of code.

Masters answered 3/2, 2011 at 3:33 Comment(2)
Indeed. The answer to the other question appears to be deliberately opaque and showoffy. The BitConverter call is much more readable and probably has no extra performance cost compared to the unsafe code (especially when taken in the context of all the crypto stuff that's going on in the answer to the other question).Guizot
@LukeH: BitConverter probably does the type-punning, but since it's in an assembly signed by Microsoft, it can be used in all sorts of partial-trust scenarios, the caller remains verifiable and after inlining in the JIT, I'd expect the machine code to be exactly the same. Subverting the type system in this particular case doesn't have any security ramifications, because BitConverter requires the inputs and outputs to be primitive numeric types.Masters

© 2022 - 2024 — McMap. All rights reserved.