Skip to Content
TUtilityBytes, conversion and checksums

Bytes, conversion and checksums

On this page

Bit operations

TUtility.BitExtension.BitHelper provides SetBit and GetBit on byte / ushort, plus selected multi-bit operations. Positions start at zero. Mutation returns a new numeric value:

using TUtility.BitExtension; ushort status = 0; status = status.SetBit(3, true); Console.WriteLine(status.GetBit(3));

Validate positions against the target width. Bit numbering and byte order are separate concerns; decode multi-byte registers using the protocol’s byte, word and bit order.

CRC16

CrcHelper.Crc16Only accepts ReadOnlySpan<byte> or segmented ReadOnlySequence<byte>. Defaults are polynomial 0xA001 and initial value 0xFFFF. It returns two CRC bytes only, low byte first:

using TUtility; byte[] payload = [0x01, 0x03, 0x00, 0x00, 0x00, 0x02]; var crc = CrcHelper.Crc16Only(payload.AsSpan()); var frame = new byte[payload.Length + crc.Length]; payload.CopyTo(frame, 0); crc.CopyTo(frame, payload.Length);

Exclude any existing CRC from the input. To validate a frame, separate payload and checksum according to its protocol. Other CRC variants can differ in initialization, reflection or final XOR; changing only the polynomial does not cover every variant.

Type conversion

TUtility.Extension.ConvertHelper includes GetTypeValue(Type, string, out object?), GetTypeStringValue and default-value conversion extensions. GetTypeValue recognizes common types and some hexadecimal numeric formats. False indicates an unsupported conversion path; internal Parse calls can still throw format or overflow exceptions.

Validate imported fields for culture, precision, nulls and ranges. Use default-value conversion only for fields permitting fallback.

Unique identifiers

using TUtility; YitIdHelper.SetIdGenerator(new IdGeneratorOptions(1)); long id = YitIdHelper.NextId(); Console.WriteLine(id);

Configure once before generating IDs. Reinitializing per request resets sequence state. Without configuration, the default uses worker 1. Multiple processes need unique WorkerIds within the configured bit width, plus deliberate clock rollback and restart handling.

Generated long values may exceed JavaScript’s safe integer range. Preserve precision in JSON and Excel identifier columns; see TAdmin JSON and TExcel mapping.