이 바이너리 패키지는 Dart에서 이진 데이터를 다루고 비트 단위 연산을 수행하기 위한 유틸리티를 제공합니다. 이는 이진 스트림의 효율적인 읽기, 쓰기 및 조작을 가능하게 하며, 시프트, 마스킹, 개별 비트 추출과 같은 비트 연산도 지원합니다. 저수준 데이터 처리, 직렬화 또는 이미지나 네트워크 프로토콜과 같은 원시 이진 형식을 다룰 때 이상적입니다. 이 패키지는 가볍고 Android, iOS, Web, macOS, Windows, Linux 등 모든 주요 플랫폼과 호환되도록 설계되었습니다.
사용 사례
이진 파일 형식 파싱
네트워크 프로토콜 핸들러 구현
원시 센서 데이터 처리
비트 단위 데이터 인코딩/디코딩
이진 직렬화 처리
사용자 지정 바이너리 코덱 만들기
주요 기능
효율적인 비트 조작
빅엔디안 및 리틀엔디안 형식 지원
스트림 기반의 이진 읽기/쓰기
크로스 플랫폼 호환성
일반적인 이진 연산을 위한 간단한 API
외부 종속성 없음
적합한 대상
이진 데이터를 다루는 개발자
하위 수준 시스템 프로그래밍
이진 자산을 사용한 게임 개발
사물인터넷 및 임베디드 시스템
네트워크 프로토콜 구현
고려 사항
고성능 핵심 애플리케이션용으로 의도되지 않음
이진 데이터 개념을 이해해야 합니다
기본 비트 연산에 제한됨
복잡한 형식을 처리하기 위해 추가적인 파싱 로직이 필요할 수 있습니다
스트리밍이 아닌 유한한 이진 데이터에 가장 적합
원본 README
연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.
Binary
Utilities for accessing binary data and bit manipulation in Dart.
[!IMPORTANT]
Version 4.0.0 has a large set of breaking changes, including removing the
vast majority of extension methods and boxed classes, in favor of using the
newer extension types feature in Dart. I would be opening to adding back
some deprecated methods, or a lib/compat.dart file if there is demand;
please file an issue if you need this.
Getting started
dart pub add binary
Then, import the package and start using it:
import'package:binary/binary.dart';
If you are not familiar with extension methods and extension types, it
is worth reading the documentation before using this package, which has heavy
use of extensions for most functionality. A small primer is instead of writing
something like:
voidmain() {
// Old API in version <= 0.1.3:print(toBinaryPadded(0x0C, 8)); // 00001100// Old API in version < 4.0.0:print(0x0C.toBinaryPadded(8)); // 00001100
}
You now use toBinaryString (and other methods) on an extension type:
voidmain() {
// New API.print(Uint8(0x0C).toBinaryString()); // 00001100
}
Notice that the width is no longer required, as the type itself knows its width.
Usage
This package provides a few sets of APIs extension types and methods.
Most users will use one of the fixed-width integer types, such as Uint8:
// Parse and reprsent a binary integer:final rawInt = int.parse('0111''1111', radix: 2);
final fixInt = Uint8(rawInt);
print(fixInt); // 127// Works identically to the >>> operator in JavaScript:final shifted = fixInt.signedRightShift(5);
print(shifted.toBinaryString()); // 00000011
Overflows
Fixed with integers do not overflow unexpectedly, unlike the core Dart types.
By default, any operation that can overflow throws an assertion error in debug
mode, and wraps around in release mode. For example:
// An error in debug mode, or 0 in release mode.Uint8(255) + Uint8(1);
To disable assertions, and always wrap, even in debug mode:
debugCheckFixedWithInRange = false;
Finer-grained control is available by using variants of the operators that
explicitly handle overflow:
// Returns null if the operation would overflow.Uint8(255).tryAdd(Uint8(1));
// Wraps around if the operation would overflow.Uint8(255).wrappedAdd(Uint8(1));
// Clamps the result to the min/max value if the operation would overflow.Uint8(255).clampedAdd(Uint8(1));
An additional variant, uncheckedAdd, is available for when you are certain
that overflow is not possible, and want to avoid the overhead of checking:
// Asserts in debug mode, no overhead in release mode, but can overflow!// OK, this will definitely not overflow.Uint8(1).uncheckedAdd(Uint8(3));
// DANGEROUS: This will overflow, but it won't be checked in release mode!Uint8(255).uncheckedAdd(Uint8(1));
Compatibility
This package is intended to work identically and well in:
The Dart VM, in both JIT and AOT modes.
Flutter, in both JIT and AOT modes.
The web, in both DDC, Dart2JS modes and compiled to WASM.
As a result, there are no built-in ways to access integers > 32-bit provided (as
JS integers are limited).
Feel free to file an issue if you'd like limited support for 64 and 128-bit
integers.
Contributing
To run the tests, run:
dart test
Or, to run a comprehensive set of tests on all supported platforms, run: