C#에서 F# CRC16 ^ 및 ^^^은 다르게 작동합니다.^는 어떻게 작동하나요?

StackOverflow https://stackoverflow.com/questions/7383781

  •  29-10-2019
  •  | 
  •  

문제

CRC16에 대한 C# 코드를 찾았지만 F#에 필요합니다.

시스템 사용;

public class Crc16 {
    const ushort polynomial = 0xA001;
    ushort[] table = new ushort[256];

    public ushort ComputeChecksum(byte[] bytes) {
        ushort crc = 0;
        for(int i = 0; i < bytes.Length; ++i) {
            byte index = (byte)(crc ^ bytes[i]);
            crc = (ushort)((crc >> 8) ^ table[index]);
        }
        return crc;
    }

    public byte[] ComputeChecksumBytes(byte[] bytes) {
        ushort crc = ComputeChecksum(bytes);
        return BitConverter.GetBytes(crc);
    }

    public Crc16() {
        ushort value;
        ushort temp;
        for(ushort i = 0; i < table.Length; ++i) {
            value = 0;
            temp = i;
            for(byte j = 0; j < 8; ++j) {
                if(((value ^ temp) & 0x0001) != 0) {
                    value = (ushort)((value >> 1) ^ polynomial);
                }else {
                    value >>= 1;
                }
                temp >>= 1;
            }
            table[i] = value;
        }
    }
}

내가 시작한 곳은 다음과 같습니다.

let ComputeChecksum(bytes : byte array) =
    let mutable crc = 0us
    for i = 0 to bytes.Length do
        let index = (crc ^^^ bytes.[i]) // ? uint16 and byte

그래서 C# 버전은 여기서 첫 번째 또는 두 번째 바이트를 사용하고 있다고 생각합니다.그래서 C# '^'이 여기서 어떻게 작동하는지 알고 싶습니다.그리고 이 C# 코드 줄을 F#으로 어떻게 변환할 수 있나요?

도움이 되었습니까?

해결책

C # 코드와 동일한 결과를 계산합니다.

type Crc16() =
  let polynomial = 0xA001us
  let table = Array.init 256 (fun i ->
    ((0us, uint16 i), [0y..7y]) 
    ||> Seq.fold (fun (value, temp) j ->
      let newValue = 
        match (value ^^^ temp) &&& 0x0001us with
        | 0us -> value >>> 1
        | _ -> ((value >>> 1) ^^^ polynomial)
      newValue, temp >>> 1)
    |> fst)
  member __.ComputeChecksum(bytes:byte[]) =
    (0us, bytes) ||> Seq.fold (fun crc byt ->
      let index = byte (crc ^^^ (uint16 byt))
      (crc >>> 8) ^^^ table.[int index])
.

다른 팁

씨# ^ 그리고 F# ^^^ 둘 다 XOR 연산자입니다.그들은 동일하게 작동해야 합니다.그게 당신이 묻는 것인가요?

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top