mirror of
https://github.com/danbulant/Cosmos
synced 2026-05-19 12:30:32 +00:00
51 lines
1.8 KiB
C#
51 lines
1.8 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
|
|
namespace Cosmos.Common.Extensions {
|
|
// This class duplicates BitConvertor. BitConvertor uses ulong though and currently does not
|
|
// work in Cosmos. But even when it does work, this syntax is more convenient and we use
|
|
// these conversions frequently.
|
|
// TODO: In the future we should find a way to inline and asm these, or maybe use way to map
|
|
// a record structure on top of a byte array for speed.
|
|
//
|
|
// BitConverter also uses platform specific endianness and cannot be changed.
|
|
// Since we read from disk, network etc we must be able to specify and change endianness.
|
|
//
|
|
// Default methods are LittleEndian
|
|
static public class ByteConverter {
|
|
|
|
static public UInt16 ToUInt16(this byte[] n, int aPos) {
|
|
return (UInt16)(n[aPos + 1] << 8 | n[aPos]);
|
|
}
|
|
|
|
static public UInt32 ToUInt32(this byte[] n, int aPos) {
|
|
return (UInt32)(n[aPos + 3] << 24 | n[aPos + 2] << 16 | n[aPos + 1] << 8 | n[aPos]);
|
|
}
|
|
|
|
static public string GetAsciiString(this byte[] n, int aStart, int aCharCount) {
|
|
var xChars = new char[aCharCount];
|
|
for (int i = 0; i < aCharCount; i++) {
|
|
xChars[i] = (char)n[aStart + i];
|
|
if (xChars[i] == 0) {
|
|
return new string(xChars, 0, i);
|
|
}
|
|
}
|
|
return new string(xChars);
|
|
}
|
|
|
|
static public string GetAscii16String(this byte[] n, int aStart, int aCharCount) {
|
|
//TODO: This routine only handles ASCII. It does not handle other types.
|
|
var xChars = new char[aCharCount];
|
|
for (int i = 0; i < aCharCount; i++) {
|
|
xChars[i] = (char)n[aStart + i * 2];
|
|
if (xChars[i] == 0) {
|
|
return new string(xChars, 0, i);
|
|
}
|
|
}
|
|
return new string(xChars);
|
|
}
|
|
|
|
}
|
|
}
|