Microsoft MVP성태의 닷넷 이야기
.NET Framework: 2047. Golang, Python, C#에서의 CRC32 사용 [링크 복사], [링크+제목 복사],
조회: 7190
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

Golang, Python, C#에서의 CRC32 사용

polyglot 시대에 ^^ 문자열의 hash를 언어 간에 일치하는 것이 필요하곤 합니다. 이럴 때 가볍게 쓸 수 있는 방법이 바로 CRC32인데요, 우선 python은 이렇게 구현할 수 있습니다.

import zlib

text = "Hello World"
hash_value = zlib.crc32(text.encode('utf-8'))

print(hash_value) // 출력 결과: 1243066710

Golang의 경우 내부에서 사용할 테이블의 생성 방법을 다양하게 제공하는데요,

const (
    // IEEE is by far and away the most common CRC-32 polynomial.
    // Used by ethernet (IEEE 802.3), v.42, fddi, gzip, zip, png, ...
    IEEE = 0xedb88320

    // Castagnoli's polynomial, used in iSCSI.
    // Has better error detection characteristics than IEEE.
    // https://dx.doi.org/10.1109/26.231911
    Castagnoli = 0x82f63b78

    // Koopman's polynomial.
    // Also has better error detection characteristics than IEEE.
    // https://dx.doi.org/10.1109/DSN.2002.1028931
    Koopman = 0xeb31d82e
)

주석을 통해 짐작할 수 있겠지만, Python과 일치하려면 IEEE 방식을 사용하면 됩니다.

package main

import (
    "fmt"
    "hash/crc32"
)

func main() {
    text := "Hello World"

    b := []byte(text)

    result := crc32.Checksum(b, crc32.MakeTable(crc32.IEEE))
    // 또는,
    // result := crc32.Checksum(b, crc32.IEEETable)
    // 또는,
    // result := crc32.ChecksumIEEE(b)

    fmt.Printf("IEEE: %v\n", result)

    result = crc32.Checksum(b, crc32.MakeTable(crc32.Castagnoli))
    fmt.Printf("Castagnoli: %v\n", result)

    result = crc32.Checksum(b, crc32.MakeTable(crc32.Koopman))
    fmt.Printf("Koopman: %v\n", result)
}

/* 출력 결과
IEEE: 1243066710
Castagnoli: 1763551791
Koopman: 1502986882
*/

마지막으로 C#은 어떨까요? 아쉽게도 기본 BCL에는 포함돼 있지 않고 nuget을 통해 (.NET Platform Extension인) 패키지 설치를 해야 합니다.

// Install-Package System.IO.Hashing -Version 6.0.1
// Install-Package System.IO.Hashing

using System.IO.Hashing;
using System.Text;

// Crc32 Class
// https://docs.microsoft.com/en-us/dotnet/api/system.io.hashing.crc32
Crc32 crc32 = new Crc32();

var bytes = Encoding.UTF8.GetBytes("Hello World");
crc32.Append(bytes);

Console.WriteLine(BitConverter.ToInt32(crc32.GetCurrentHash())); // 1243066710

사실 CRC 코드가 워낙 간단해서,

// Crc32.cs

private static uint Update(uint crc, ReadOnlySpan<byte> source)
{
    for (int i = 0; i < source.Length; i++)
    {
        byte idx = (byte)crc;
        idx ^= source[i];
        crc = s_crcLookup[idx] ^ (crc >> 8);
    }

    return crc;
}

직접 각 언어별로 만들어서 사용해 됩니다. 단지 Python의 경우는 C 언어로 만들어진 zlib의 native 코드가 실행되는 것이므로 성능을 생각한다면 직접 만드는 것은 좋은 선택이 아닙니다.




참고로, 한 가지 주의 사항이 있는데요, 언어마다 다른 자료형으로 인해 음수를 가질 수 있는 hash 값에 대한 후처리가 필요할 수 있습니다. 가령 "ed43aa2a-586d-46b2-b103-92e17bf00eaf"라는 문자열은 언어마다 다른 출력을 갖습니다.

// "ed43aa2a-586d-46b2-b103-92e17bf00eaf" CRC-32 결과

Python: 2811875030
Golang: 2811875030
C#: -1483092266

가령 Golang의 경우 int 타입을 반환하는데 이것은 64비트에 해당하므로 0x80_00_00_00 이상의 값을 음수가 아닌 양수로 표현할 수 있습니다. 반면, C#은 부호 있는 4바이트이므로 0x7f_00_00_00(2,147,483,647)를 넘으면 음수로 표현하는 것입니다.

그래서 해당 값을 언어 간에 직렬화/역직렬화 시 그에 대한 처리가 필요할 수 있습니다. 가령, Golang에서 직렬화한 "2811875030" 값을 C#에서 단순히 Int.Parse로 복원하면,

// 예외 발생
// Unhandled exception. System.OverflowException: Value was either too large or too small for an Int32.
int result = int.Parse("2811875030");

예외가 발생하므로, 정확한 바이트 범위를 서로 간에 약속해야 합니다. 가령 long으로 처리할지, 아니면 4바이트 부호 있는 정수로 합의하면 되는데, 후자로 정했다면 파이썬은 이런 식으로 처리를 추가해야 합니다.

// How to get the signed integer value of a long in python?
// ; https://stackoverflow.com/questions/1375897/how-to-get-the-signed-integer-value-of-a-long-in-python
import zlib
import ctypes

text = "ed43aa2a-586d-46b2-b103-92e17bf00eaf"
hash_value = zlib.crc32(text.encode('utf-8'))
hash_value = hash_value & 0xFFFFFFFF
hash_value = ctypes.c_int32(hash_value).value

print(hash_value) // 출력 결과: -1483092266

반면 Golang은 간단하게 형변환만 하면 됩니다.

var result int32
result = int32(crc32.Checksum(b, crc32.IEEETable))




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 9/14/2022]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 16  17  18  19  20  21  22  23  [24]  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13035정성태4/22/20227675Windows: 204. Windows 10부터 바뀐 QueryPerformanceFrequency, QueryPerformanceCounter
13034정성태4/21/20227024.NET Framework: 1996. C# XingAPI - 주식 종목에 따른 PBR, PER, ROE, ROA 구하는 방법(t3320, t8430 예제)파일 다운로드1
13033정성태4/18/20227624.NET Framework: 1195. C# - Thread.Yield와 Thread.Sleep(0)의 차이점(?)
13032정성태4/17/20227350오류 유형: 805. Github의 50MB 파일 크기 제한 - warning: GH001: Large files detected. You may want to try Git Large File Storage
13031정성태4/15/20226889.NET Framework: 1194. C# - IdealProcessor와 ProcessorAffinity의 차이점
13030정성태4/15/20226541오류 유형: 804. 정규 표현식 오류 - Quantifier {x,y} following nothing.
13029정성태4/14/20226965Windows: 203. iisreset 후에도 이전에 설정한 전역 환경 변수가 w3wp.exe에 적용되는 문제
13028정성태4/13/20226883.NET Framework: 1193. (appsettings.json처럼) web.config의 Debug/Release에 따른 설정 적용
13027정성태4/12/20227153.NET Framework: 1192. C# - 환경 변수의 변화를 알리는 WM_SETTINGCHANGE Win32 메시지 사용법파일 다운로드1
13026정성태4/11/20228705.NET Framework: 1191. C 언어로 작성된 FFmpeg Examples의 C# 포팅 전체 소스 코드 [3]
13025정성태4/11/20228055.NET Framework: 1190. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 vaapi_encode.c, vaapi_transcode.c 예제 포팅
13024정성태4/7/20226559.NET Framework: 1189. C# - 런타임 환경에 따라 달라진 AppDomain.GetCurrentThreadId 메서드
13023정성태4/6/20226856.NET Framework: 1188. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 transcoding.c 예제 포팅 [3]
13022정성태3/31/20226754Windows: 202. 윈도우 11 업그레이드 - "PC Health Check"를 통과했지만 여전히 업그레이드가 안 되는 경우 해결책
13021정성태3/31/20226939Windows: 201. Windows - INF 파일을 이용한 장치 제거 방법
13020정성태3/30/20226693.NET Framework: 1187. RDP 접속 시 WPF UserControl의 Unloaded 이벤트 발생파일 다운로드1
13019정성태3/30/20226657.NET Framework: 1186. Win32 Message를 Code로부터 메시지 이름 자체를 구하고 싶다면?파일 다운로드1
13018정성태3/29/20227180.NET Framework: 1185. C# - Unsafe.AsPointer가 반환한 포인터는 pinning 상태일까요? [5]
13017정성태3/28/20226963.NET Framework: 1184. C# - GC Heap에 위치한 참조 개체의 주소를 알아내는 방법 - 두 번째 이야기 [3]
13016정성태3/27/20227848.NET Framework: 1183. C# 11에 추가된 ref 필드의 (우회) 구현 방법파일 다운로드1
13015정성태3/26/20229183.NET Framework: 1182. C# 11 - ref struct에 ref 필드를 허용 [1]
13014정성태3/23/20227755VC++: 155. CComPtr/CComQIPtr과 Conformance mode 옵션의 충돌 [1]
13013정성태3/22/20226060개발 환경 구성: 641. WSL 우분투 인스턴스에 파이썬 2.7 개발 환경 구성하는 방법
13012정성태3/21/20225388오류 유형: 803. C# - Local '...' or its members cannot have their address taken and be used inside an anonymous method or lambda expression
13011정성태3/21/20226910오류 유형: 802. 윈도우 운영체제에서 웹캠 카메라 인식이 안 되는 경우
13010정성태3/21/20225831오류 유형: 801. Oracle.ManagedDataAccess.Core - GetTypes 호출 시 "Could not load file or assembly 'System.DirectoryServices.Protocols...'" 오류
... 16  17  18  19  20  21  22  23  [24]  25  26  27  28  29  30  ...