Here are the examples of the csharp api System.Convert.ToByte(char) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
74 Examples
19
Source : SimpleAudioRecorderImplementation.cs
with MIT License
from adrianstevens
with MIT License
from adrianstevens
void WriteWaveFileHeader(FileOutputStream outputStream, long audioLength, long dataLength, long sampleRate, int channels, long byteRate)
{
byte[] header = new byte[44];
header[0] = Convert.ToByte('R'); // RIFF/WAVE header
header[1] = Convert.ToByte('I'); // (byte)'I'
header[2] = Convert.ToByte('F');
header[3] = Convert.ToByte('F');
header[4] = (byte)(dataLength & 0xff);
header[5] = (byte)((dataLength >> 8) & 0xff);
header[6] = (byte)((dataLength >> 16) & 0xff);
header[7] = (byte)((dataLength >> 24) & 0xff);
header[8] = Convert.ToByte('W');
header[9] = Convert.ToByte('A');
header[10] = Convert.ToByte('V');
header[11] = Convert.ToByte('E');
header[12] = Convert.ToByte('f'); // fmt chunk
header[13] = Convert.ToByte('m');
header[14] = Convert.ToByte('t');
header[15] = (byte)' ';
header[16] = 16; // 4 bytes - size of fmt chunk
header[17] = 0;
header[18] = 0;
header[19] = 0;
header[20] = 1; // format = 1
header[21] = 0;
header[22] = Convert.ToByte(channels);
header[23] = 0;
header[24] = (byte)(sampleRate & 0xff);
header[25] = (byte)((sampleRate >> 8) & 0xff);
header[26] = (byte)((sampleRate >> 16) & 0xff);
header[27] = (byte)((sampleRate >> 24) & 0xff);
header[28] = (byte)(byteRate & 0xff);
header[29] = (byte)((byteRate >> 8) & 0xff);
header[30] = (byte)((byteRate >> 16) & 0xff);
header[31] = (byte)((byteRate >> 24) & 0xff);
header[32] = (byte)(2 * 16 / 8); // block align
header[33] = 0;
header[34] = Convert.ToByte(16); // bits per sample
header[35] = 0;
header[36] = Convert.ToByte('d');
header[37] = Convert.ToByte('a');
header[38] = Convert.ToByte('t');
header[39] = Convert.ToByte('a');
header[40] = (byte)(audioLength & 0xff);
header[41] = (byte)((audioLength >> 8) & 0xff);
header[42] = (byte)((audioLength >> 16) & 0xff);
header[43] = (byte)((audioLength >> 24) & 0xff);
outputStream.Write(header, 0, 44);
}
19
Source : DataBuffer.cs
with MIT License
from AndreasAmMueller
with MIT License
from AndreasAmMueller
public void SetChar(int index, char value)
=> SetByte(index, Convert.ToByte(value));
19
Source : DataBuffer.cs
with MIT License
from AndreasAmMueller
with MIT License
from AndreasAmMueller
public void AddChar(char value)
=> AddByte(Convert.ToByte(value));
19
Source : CryptoService.cs
with MIT License
from ansel86castro
with MIT License
from ansel86castro
public static byte[] FromStringX2(string data)
{
if (data.Length % 2 != 0)
throw new InvalidOperationException($"Invalid format {nameof(data)}");
var bytes = new byte[data.Length / 2];
for (int i = 0; i < bytes.Length; i++)
{
byte b = Convert.ToByte(data[i * 2]);
b = (byte)(b << 4 | Convert.ToByte(data[i * 2 + 1]));
bytes[i] = b;
}
return bytes;
}
19
Source : B3dm.cs
with MIT License
from arcplus
with MIT License
from arcplus
public byte[] Convert(Options options)
{
if (options == null) options = new Options();
var featureTableJson = options.FeatureTableJson;
var featureTableBinary = options.FeatureTableBinary;
var batchTableJson = options.BatchTableJson;
var batchTableBinary = options.BatchTableBinary;
var featureTableJsonByteLength = featureTableJson.Count;
var featureTableBinaryByteLength = featureTableBinary.Count;
var batchTableJsonByteLength = batchTableJson.Count;
var batchTableBinaryByteLength = batchTableBinary.Count;
var gltfByteLength = _glb.Count;
var byteLength = HeaderByteLength + featureTableJsonByteLength
+ featureTableBinaryByteLength + batchTableJsonByteLength
+ batchTableBinaryByteLength + gltfByteLength;
var all = new List<byte>();
// Header
all.Add(System.Convert.ToByte('b'));
all.Add(System.Convert.ToByte('3'));
all.Add(System.Convert.ToByte('d'));
all.Add(System.Convert.ToByte('m'));
all.AddRange(BitConverter.GetBytes((uint)Version));
all.AddRange(BitConverter.GetBytes((uint)byteLength));
all.AddRange(BitConverter.GetBytes((uint)featureTableJsonByteLength));
all.AddRange(BitConverter.GetBytes((uint)featureTableBinaryByteLength));
all.AddRange(BitConverter.GetBytes((uint)batchTableJsonByteLength));
all.AddRange(BitConverter.GetBytes((uint)batchTableBinaryByteLength));
all.AddRange(featureTableJson);
all.AddRange(featureTableBinary);
all.AddRange(batchTableJson);
all.AddRange(batchTableBinary);
all.AddRange(_glb);
return all.ToArray();
}
19
Source : Program.cs
with MIT License
from Arefu
with MIT License
from Arefu
[STAThread]
private static void Main()
{
Console.replacedle = "Lithe";
var Credits = "";
using (var Ofd = new OpenFileDialog())
{
Ofd.replacedle = "Select Credits To Encode/Decode";
Ofd.Filter = "Credits file (*.dat, *.txt) | *.dat; *.txt";
if (Ofd.ShowDialog() == DialogResult.OK)
Credits = Ofd.FileName;
else
Environment.Exit(1);
}
if (Utilities.IsExt(Credits, ".dat"))
{
using (var Reader = new BinaryReader(File.Open(Credits, FileMode.Open, FileAccess.Read)))
{
var CreditsContent = Reader.ReadBytes((int) new FileInfo(Credits).Length);
File.WriteAllText("credits.txt",
Encoding.Unicode.GetString(CreditsContent)
.Replace("?",
string.Empty)); //Two Start Characters Are A Magic Byte Letting The Game Know To In-Line Images
Utilities.Log("Finished Parsing.", Utilities.Event.Information);
}
}
else
{
using (var Writer = new BinaryWriter(File.Open("credits.dat", FileMode.Append, FileAccess.Write)))
{
using (var Reader =
new BinaryReader(File.Open("credits.txt", FileMode.OpenOrCreate, FileAccess.Read)))
{
var Content = Reader.ReadBytes((int) Reader.BaseStream.Length);
Writer.Write(new byte[] {0xFF, 0xFE});
foreach (var Char in Encoding.ASCII.GetString(Content))
switch (Char)
{
case '\r':
Writer.Write(new byte[] {0x0D, 0x00});
break;
case '\n':
Writer.Write(new byte[] {0x0A, 0x00});
break;
default:
Writer.Write(new byte[] {Convert.ToByte(Char), 0x00});
break;
}
}
}
Utilities.Log("Finished Encoding.", Utilities.Event.Information);
}
}
19
Source : Main.cs
with MIT License
from arsium
with MIT License
from arsium
private void generateKeyButton_Click(object sender, EventArgs e)
{
try
{
Random randomGenerator = new Random();
List<byte> RES = new List<byte>();
StringBuilder S = new StringBuilder();
for (var i = 0; i <= 450; i++)
{
S.Append(Utilities.randomString[randomGenerator.Next(0, Utilities.randomString.Length)]);
}
switch (keySizeComboBox.SelectedItem)
{
case "Any":
int tempVar = 32 + randomGenerator.Next(0, 128) - 1;
for (var i = 0; i <= tempVar; i++)
{
RES.Add(Convert.ToByte(S.ToString()[i]));
}
keyTextBox.Text = Encoding.Default.GetString(RES.ToArray());
break;
case "32-448":
int tempVar2 = (randomGenerator.Next(32, 448) - 1) / 8;
for (var i = 0; i <= tempVar2; i++)
{
RES.Add(Convert.ToByte(S.ToString()[i]));
}
keyTextBox.Text = Encoding.Default.GetString(RES.ToArray());
break;
case "128-512":
int tempVar3 = (randomGenerator.Next(128, 512) - 1) / 8;
for (var i = 0; i <= tempVar3; i++)
{
RES.Add(Convert.ToByte(S.ToString()[i]));
}
keyTextBox.Text = Encoding.Default.GetString(RES.ToArray());
break;
case "40-2048":
int tempVar4 = (randomGenerator.Next(40, 2048) - 1) / 8;
for (var i = 0; i <= tempVar4; i++)
{
RES.Add(Convert.ToByte(S.ToString()[i]));
}
keyTextBox.Text = Encoding.Default.GetString(RES.ToArray());
break;
case "8-2048":
int tempVar5 = (randomGenerator.Next(8, 2048) - 1) / 8;
for (var i = 0; i <= tempVar5; i++)
{
RES.Add(Convert.ToByte(S.ToString()[i]));
}
keyTextBox.Text = Encoding.Default.GetString(RES.ToArray());
break;
default:
int tempVar6 = (int.Parse(keySizeComboBox.SelectedItem.ToString()) - 1) / 8;
for (var i = 0; i <= tempVar6; i++)
{
RES.Add(Convert.ToByte(S.ToString()[i]));
}
keyTextBox.Text = Encoding.Default.GetString(RES.ToArray());
break;
}
Utilities.key = Encoding.Default.GetString(RES.ToArray());
Utilities.settings.encryptionFileManagerKey = Utilities.key;
Utilities.settings.encryptionFileManagerKeySize = keySizeComboBox.SelectedItem.ToString();
Utilities.settings.algorithm = (Algorithm)(algoComboBox.SelectedIndex);
string savedSettings = JsonConvert.SerializeObject(Utilities.settings);
File.WriteAllText(Utilities.GPath + "\\config.json", savedSettings);
}
catch {}
}
19
Source : EnumUtil.cs
with GNU General Public License v3.0
from audiamus
with GNU General Public License v3.0
from audiamus
public static string ToDisplayString<TEnum, TPunct> (this TEnum value, ResourceManager rm)
where TEnum: struct, Enum
where TPunct : clreplaced, IChainPunctuation, new()
{
var punct = Singleton<TPunct>.Instance;
string sval = value.ToString ();
//verbatim ?
if (sval.StartsWith ("_")) {
return rm.GetStringEx (sval.Substring (1));
}
string[] parts = sval.Split (USCORE);
bool noSubsreplacedutes = parts.Select (s => s.Length).Min () > 1;
StringBuilder sb = new StringBuilder ();
if (noSubsreplacedutes) {
for (int i = 0; i < parts.Length; i++)
parts[i] = punct.Prefix + rm.GetStringEx (parts[i]) + punct.Suffix;
foreach (string s in parts) {
if (sb.Length > 0)
sb.Append (punct.Infix?[0]);
sb.Append (s);
}
} else {
for (int i = 0; i < parts.Length; i++) {
if (parts[i].Length > 1)
parts[i] = punct.Prefix + rm.GetStringEx (parts[i]) + punct.Suffix;
else {
byte x = Convert.ToByte (parts[i][0]);
try {
parts[i] = punct.Infix?[x - __a];
} catch (IndexOutOfRangeException) {
parts[i] = string.Empty;
}
}
}
foreach (string s in parts)
sb.Append (s);
}
return sb.ToString ();
}
19
Source : Utils.cs
with MIT License
from bestyize
with MIT License
from bestyize
public static string convertToHexString(string str)
{
string hexString = "";
char[] strChars = str.ToCharArray();
foreach (char c in strChars)
{
hexString += Convert.ToByte(c).ToString("X2") + " ";
}
if (hexString.EndsWith(" "))
{
hexString = hexString.Substring(0, hexString.LastIndexOf(" "));
}
return hexString;
}
19
Source : ZplTextField.cs
with MIT License
from BinaryKits
with MIT License
from BinaryKits
private string SanitizeCharacter(char input)
{
if (UseHexadecimalIndicator)
{
//Convert to hex
switch (input)
{
case '_':
case '^':
case '~':
return "_" + Convert.ToByte(input).ToString("X2");
case '\\':
return " ";
}
}
else
{
//The field data can be any printable character except those used as command prefixes(^ and ~).
//Replace '^', '~'
switch (input)
{
case '^':
case '~':
case '\\':
return " ";
}
}
if (input == '\n')
{
switch (NewLineConversion)
{
case NewLineConversionMethod.ToEmpty:
return "";
case NewLineConversionMethod.ToSpace:
return " ";
case NewLineConversionMethod.ToZplNewLine:
return @"\&";
}
}
return input.ToString();
}
19
Source : ZplEngine.cs
with MIT License
from BinaryKits
with MIT License
from BinaryKits
static public string MapToHexadecimalValue(char input)
{
return Convert.ToByte(input).ToString("X2");
}
19
Source : BufferBinaryWriter.cs
with MIT License
from colinator27
with MIT License
from colinator27
public void Write(char[] value)
{
ResizeToFit(offset + value.Length);
foreach (char c in value)
buffer[offset++] = Convert.ToByte(c);
}
19
Source : Crypto.cs
with BSD 3-Clause "New" or "Revised" License
from cube0x0
with BSD 3-Clause "New" or "Revised" License
from cube0x0
public static byte[] DeriveKey(byte[] keyBytes, byte[] saltBytes, int algHash)
{
// derives a dpapi session key using Microsoft crypto "magic"
// calculate the session key -> HMAC(salt) where the sha1(masterkey) is the key
if (algHash == 32782)
{
// 32782 == CALG_SHA_512
return HMACSha512(keyBytes, saltBytes);
}
else if (algHash == 32772)
{
// 32772 == CALG_SHA1
var hmac = new HMACSHA1(keyBytes);
var sessionKeyBytes = hmac.ComputeHash(saltBytes);
var ipad = new byte[64];
var opad = new byte[64];
// "...wut" - anyone reading Microsoft crypto
for (var i = 0; i < 64; i++)
{
ipad[i] = Convert.ToByte('6');
opad[i] = Convert.ToByte('\\');
}
for (var i = 0; i < keyBytes.Length; i++)
{
ipad[i] ^= sessionKeyBytes[i];
opad[i] ^= sessionKeyBytes[i];
}
using (var sha1 = new SHA1Managed())
{
var ipadSHA1bytes = sha1.ComputeHash(ipad);
var opadSHA1bytes = sha1.ComputeHash(opad);
var combined = Helpers.Combine(ipadSHA1bytes, opadSHA1bytes);
return combined;
}
}
else
{
return new byte[0];
}
}
19
Source : CharAdvancedConverter.cs
with MIT License
from DataObjects-NET
with MIT License
from DataObjects-NET
byte IAdvancedConverter<char, byte>.Convert(char value)
{
return System.Convert.ToByte(value);
}
19
Source : Strings.cs
with MIT License
from dcomms
with MIT License
from dcomms
public static byte[] ToByteArray(
char[] cs)
{
byte[] bs = new byte[cs.Length];
for (int i = 0; i < bs.Length; ++i)
{
bs[i] = Convert.ToByte(cs[i]);
}
return bs;
}
19
Source : Strings.cs
with MIT License
from dcomms
with MIT License
from dcomms
public static byte[] ToByteArray(
string s)
{
byte[] bs = new byte[s.Length];
for (int i = 0; i < bs.Length; ++i)
{
bs[i] = Convert.ToByte(s[i]);
}
return bs;
}
19
Source : MapHandler.cs
with GNU General Public License v3.0
from DigiWorm0
with GNU General Public License v3.0
from DigiWorm0
public static bool Load()
{
if (mapLoaded)
return true;
LILogger.LogInfo("...Deserializing Map Data");
// Get Directory
string dllDir = System.Reflection.replacedembly.Getreplacedembly(typeof(LevelImposter.MainHarmony)).Location;
mapDir = Path.Combine(Path.GetDirectoryName(dllDir), "map.json");
// Load File
if (!File.Exists(mapDir))
{
LILogger.LogError("Could not find map at " + mapDir);
return false;
}
string mapJson = File.ReadAllText(mapDir);
// Settings
var settings = new Newtonsoft.Json.JsonSerializerSettings {
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore
};
// Deserialize
try
{
mapData = Newtonsoft.Json.JsonConvert.DeserializeObject<MapData>(mapJson, settings);
}
catch (Exception e)
{
LILogger.LogError("There was an error deserializing map data:\n" + e.Message);
return false;
}
// Checksum
int checkNum = 0;
foreach (char c in mapJson)
{
checkNum += Convert.ToByte(c);
}
checksum = checkNum.ToString("X4");
// Return
mapLoaded = true;
return true;
}
19
Source : BasicConvert.Overload.cs
with MIT License
from Dogwei
with MIT License
from Dogwei
byte IXConverter<char, byte>.Convert(char value)
=> Convert.ToByte(value);
19
Source : Strings.cs
with GNU General Public License v3.0
from DSorlov
with GNU General Public License v3.0
from DSorlov
public static byte[] ToByteArray(
string s)
{
byte[] bs = new byte[s.Length];
for (int i = 0; i < bs.Length; ++i)
{
bs[i] = Convert.ToByte(s[i]);
}
return bs;
}
19
Source : GeneralRecordWrapper.cs
with GNU Lesser General Public License v3.0
from faib920
with GNU Lesser General Public License v3.0
from faib920
public virtual byte GetByte(IDataRecord reader, int i)
{
if (reader.IsDBNull(i))
{
return 0;
}
var type = reader.GetFieldType(i);
if (type == typeof(byte))
{
return reader.GetByte(i);
}
else if (type == typeof(char))
{
return Convert.ToByte(reader.GetChar(i));
}
else if (type == typeof(short))
{
return Convert.ToByte(reader.GetInt16(i));
}
else if (type == typeof(int))
{
return Convert.ToByte(reader.GetInt32(i));
}
else if (type == typeof(long))
{
return Convert.ToByte(reader.GetInt64(i));
}
else if (type == typeof(decimal))
{
return Convert.ToByte(reader.GetDecimal(i));
}
else if (type == typeof(float))
{
return Convert.ToByte(reader.GetFloat(i));
}
else if (type == typeof(double))
{
return Convert.ToByte(reader.GetDouble(i));
}
return Convert.ToByte(GetValue(reader, i));
}
19
Source : Serialization.cs
with MIT License
from Greavesy1899
with MIT License
from Greavesy1899
public static void WriteChunk(char a, char b, char c, char d, BinaryWriter writer)
{
writer.Write(Convert.ToByte(a));
writer.Write(Convert.ToByte(b));
writer.Write(Convert.ToByte(c));
writer.Write(Convert.ToByte(d));
}
19
Source : Serialization.cs
with MIT License
from Greavesy1899
with MIT License
from Greavesy1899
public static void WriteChunk(char a, char b, char c, bool d, BinaryWriter writer)
{
writer.Write(Convert.ToByte(a));
writer.Write(Convert.ToByte(b));
writer.Write(Convert.ToByte(c));
writer.Write(Convert.ToByte(d));
}
19
Source : BinBVHAnimation.cs
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid
public static byte[] WriteNullTerminatedString(string str)
{
byte[] output = new byte[str.Length + 1];
Char[] chr = str.ToCharArray();
int i = 0;
for (i = 0; i < chr.Length; i++)
{
output[i] = Convert.ToByte(chr[i]);
}
output[i] = Convert.ToByte('\0');
return output;
}
19
Source : StringViewHandler.cs
with GNU Affero General Public License v3.0
from hamflx
with GNU Affero General Public License v3.0
from hamflx
private void HandleUserInput(char key)
{
if (!_editor.CaretFocused)
return;
HandleUserRemove();
byte newByte = Convert.ToByte(key);
if (_editor.HexTableLength <= 0)
_editor.AppendByte(newByte);
else
_editor.InsertByte(_editor.CaretIndex, newByte);
int index = _editor.CaretIndex + 1;
Point newLocation = GetCaretLocation(index);
_editor.SetCaretStart(index, newLocation);
}
19
Source : UnityVMDReader.cs
with MIT License
from hobosore
with MIT License
from hobosore
public void LoadFromStream(BinaryReader binaryReader)
{
try
{
char[] buffer = new char[30];
//ファイルタイプの読み込み
string RightFileType = "Vocaloid Motion Data";
byte[] fileTypeBytes = binaryReader.ReadBytes(30);
string fileType = System.Text.Encoding.GetEncoding("shift_jis").GetString(fileTypeBytes).Substring(0, RightFileType.Length);
if (!fileType.Equals("Vocaloid Motion Data"))
{
Debug.Log("読み込もうとしたファイルはVMDファイルではありません");
}
//バージョンの読み込み、バージョンは後で使用していない
Version = BitConverter.ToSingle((from c in buffer select Convert.ToByte(c)).ToArray(), 0);
//モーション名の読み込み、Shift_JISで保存されている
byte[] nameBytes = binaryReader.ReadBytes(20);
MotionName = System.Text.Encoding.GetEncoding("shift_jis").GetString(nameBytes);
//ヌル文字除去
MotionName = MotionName.TrimEnd('\0').TrimEnd('?').TrimEnd('\0');
//人ボーンのキーフレームの読み込み
int boneFrameCount = binaryReader.ReadInt32();
for (int i = 0; i < boneFrameCount; i++)
{
BoneKeyFrames.Add(new BoneKeyFrame(binaryReader));
}
//表情モーフのキーフレームの読み込み
int faceFrameCount = binaryReader.ReadInt32();
for (int i = 0; i < faceFrameCount; i++)
{
FaceKeyFrames.Add(new FaceKeyFrame(binaryReader));
}
FaceKeyFrames = FaceKeyFrames.OrderBy(x => x.FrameNumber).ToList();
//カメラのキーフレームの読み込み
int cameraFrameCount = binaryReader.ReadInt32();
for (int i = 0; i < cameraFrameCount; i++)
{
CameraFrames.Add(new CameraKeyFrame(binaryReader));
}
CameraFrames = CameraFrames.OrderBy(x => x.Frame).ToList();
//照明のキーフレームの読み込み
int lightFrameCount = binaryReader.ReadInt32();
for (int i = 0; i < lightFrameCount; i++)
{
LightFrames.Add(new LightKeyFrame(binaryReader));
}
LightFrames = LightFrames.OrderBy(x => x.Frame).ToList();
//vmdのバージョンによってはここで終わる
if (binaryReader.BaseStream.Position == binaryReader.BaseStream.Length) { return; }
//セルフシャドウの読み込み
int selfShadowFrameCount = binaryReader.ReadInt32();
for (int i = 0; i < selfShadowFrameCount; i++)
{
SelfShadowKeyFrames.Add(new SelfShadowKeyFrame(binaryReader));
}
SelfShadowKeyFrames = SelfShadowKeyFrames.OrderBy(x => x.Frame).ToList();
//vmdのバージョンによってはここで終わる
if (binaryReader.BaseStream.Position == binaryReader.BaseStream.Length) { return; }
//IKのキーフレームの読み込み
int ikFrameCount = binaryReader.ReadInt32();
for (int i = 0; i < ikFrameCount; i++)
{
IKFrames.Add(new IKKeyFrame(binaryReader));
}
//ここで終わってないとおかしい
if (binaryReader.BaseStream.Position != binaryReader.BaseStream.Length)
{
Debug.Log("データの最後に不明な部分があります");
}
return;
}
catch
{
Debug.Log("VMD読み込みエラー");
return;
}
}
19
Source : Plist.cs
with MIT License
from huailiang
with MIT License
from huailiang
private static byte[] writeBinaryString(string value, bool head)
{
List<byte> buffer = new List<byte>();
List<byte> header = new List<byte>();
foreach (char chr in value.ToCharArray())
buffer.Add(Convert.ToByte(chr));
if (head)
{
if (value.Length < 15)
{
header.Add(Convert.ToByte(0x50 | Convert.ToByte(value.Length)));
}
else
{
header.Add(0x50 | 0xf);
header.AddRange(writeBinaryInteger(buffer.Count, false));
}
}
buffer.InsertRange(0, header);
objectTable.InsertRange(0, buffer);
return buffer.ToArray();
}
19
Source : SendKeys.cs
with MIT License
from inthehand
with MIT License
from inthehand
internal static Keys ToVirtualKey(char c)
{
bool shift = false;
byte vKey = Convert.ToByte(c);
//letters
if (Char.IsUpper(c))
{
shift = true;
}
else if (Char.IsLower(c))
{
vKey = (byte)Char.ToUpper(c);
}
/*else if (Char.IsDigit(c))
{
vKey = (byte)c;
}*/
else
{
switch (c)
{
case '!':
vKey = 49;
shift = true;
break;
case '@':
vKey = 50;
shift = true;
break;
case '#':
vKey = 51;
shift = true;
break;
case '$':
vKey = 52;
shift = true;
break;
case '%':
vKey = 53;
shift = true;
break;
case '^':
vKey = 54;
shift = true;
break;
case '&':
vKey = 55;
shift = true;
break;
case '*':
vKey = 56;
shift = true;
break;
case '(':
vKey = 57;
shift = true;
break;
case ')':
vKey = 48;
shift = true;
break;
case ';':
vKey = 186;
break;
case ':':
vKey = 186;
shift = true;
break;
case '=':
vKey = 187;
break;
case '+':
vKey = 187;
shift = true;
break;
case ',':
vKey = 188;
break;
case '<':
vKey = 188;
shift = true;
break;
case '-':
vKey = 189;
break;
case '_':
vKey = 189;
shift = true;
break;
case '.':
vKey = 190;
break;
case '>':
vKey = 190;
shift = true;
break;
case '/':
vKey = 191;
break;
case '?':
vKey = 191;
shift = true;
break;
case '`':
vKey = 193;
break;
case '�':
vKey = 194;
shift = true;
break;
case '[':
vKey = 219;
break;
case '{':
vKey = 219;
shift = true;
break;
case '\\':
vKey = 220;
break;
case '|':
vKey = 220;
shift = true;
break;
case ']':
vKey = 221;
break;
case '}':
vKey = 221;
shift = true;
break;
case '\t':
vKey = (byte)Keys.Tab;
break;
case '~':
//enter
vKey = (byte)Keys.Enter;
break;
}
}
if (shift)
{
return (Keys)vKey | Keys.Shift;
}
else
{
return (Keys)vKey;
}
}
19
Source : MainForm.cs
with GNU General Public License v3.0
from jefrisibarani
with GNU General Public License v3.0
from jefrisibarani
private void SendData(int length)
{
if (!client.Connected)
return;
int byteLength = length;
byte[] dataToSend = new Byte[byteLength];
char cx = 'X';
for (int i = 0; i < byteLength; i++)
{
byte bx1 = (byte)cx;
byte bx2 = Convert.ToByte(cx);
dataToSend[i] = bx2;
if (i== byteLength-1)
dataToSend[i] = Convert.ToByte('_');
}
string txt = Encoding.ASCII.GetString(dataToSend, 0, dataToSend.Length);
int lgth = txt.Length;
client.Send(txt);
}
19
Source : FileUtil.cs
with MIT License
from jianxuanbing
with MIT License
from jianxuanbing
public static bool KillFile(string fileName, int deleteCount, bool randomData = true, bool blanks = false)
{
const int bufferLength = 1024000;
bool ret = true;
try
{
using (
FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite,
FileShare.ReadWrite))
{
FileInfo file = new FileInfo(fileName);
long count = file.Length;
long offset = 0;
var rowDataBuffer = new byte[bufferLength];
while (count >= 0)
{
int iNumOfDataRead = stream.Read(rowDataBuffer, 0, bufferLength);
if (iNumOfDataRead == 0)
{
break;
}
if (randomData)
{
Random randomByte = new Random();
randomByte.NextBytes(rowDataBuffer);
}
else if (blanks)
{
for (int i = 0; i < iNumOfDataRead; i++)
{
rowDataBuffer[i] = Convert.ToByte(Convert.ToChar(deleteCount));
}
}
//写新内容到文件
for (int i = 0; i < deleteCount; i++)
{
stream.Seek(offset, SeekOrigin.Begin);
stream.Write(rowDataBuffer, 0, iNumOfDataRead);
;
}
offset += iNumOfDataRead;
count -= iNumOfDataRead;
}
}
//每一个文件名字符代替随机数从0到9
string newName = "";
do
{
Random random = new Random();
string cleanName = Path.GetFileName(fileName);
string dirName = Path.GetDirectoryName(fileName);
int iMoreRandomLetters = random.Next(9);
//为了更安全,不要只使用原文件名的大小,添加一些随机字母
for (int i = 0; i < cleanName.Length + iMoreRandomLetters; i++)
{
newName += random.Next(9).ToString();
}
newName = dirName + "\\" + newName;
} while (File.Exists(newName));
//重命名文件的新随机的名字
File.Move(fileName, newName);
File.Delete(newName);
}
catch
{
//可能其他原因删除失败,使用我们自己的方法强制删除
try
{
string filename = fileName;//要检查被哪个进程占用的文件
Process tool = new Process()
{
StartInfo =
{
FileName = "handle.exe",
Arguments = filename + " /accepteula",
UseShellExecute = false,
RedirectStandardOutput = true
}
};
tool.Start();
tool.WaitForExit();
string outputTool = tool.StandardOutput.ReadToEnd();
string matchPattern = @"(?<=\s+pid:\s+)\b(\d+)\b(?=\s+)";
foreach (Match match in Regex.Matches(outputTool, matchPattern))
{
//结束掉所有正在使用这个文件的程序
Process.GetProcessById(int.Parse(match.Value)).Kill();
}
File.Delete(filename);
}
catch
{
ret = false;
}
}
return ret;
}
19
Source : Program.cs
with GNU General Public License v3.0
from jo3bingham
with GNU General Public License v3.0
from jo3bingham
static void BeginReceiveWorldNameCallback(IAsyncResult ar)
{
try
{
if (_clientSocket == null)
{
return;
}
var count = _clientSocket.EndReceive(ar);
if (count <= 0)
{
return;
}
// The first message the client sends to the game server is the world name without a length.
// Read from the socket one byte at a time until the end of the string (\n) is read.
while (_clientBuffer[count - 1] != Convert.ToByte('\n'))
{
var read = _clientSocket.Receive(_clientBuffer, count, 1, SocketFlags.None);
if (read <= 0)
{
throw new Exception("Client connection broken.");
}
count += read;
}
// Confirm that the client is trying to connect to us by checking the world name.
var worldName = Encoding.UTF8.GetString(_clientBuffer, 0, count - 1);
if (!worldName.Equals(OxWorldName, StringComparison.CurrentCultureIgnoreCase))
{
throw new Exception($"World name does not match `{OxWorldName}`: {worldName}");
}
var loginChallengeMessage = new NetworkMessage(_client)
{
SequenceNumber = 0
};
var loginChallengePacket = new LoginChallenge(_client)
{
Timestamp = (uint)DateTime.Now.Subtract(new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds,
Random = 0xFF
};
loginChallengePacket.AppendToNetworkMessage(loginChallengeMessage);
SendToClient(loginChallengeMessage);
_clientSocket.BeginReceive(_clientBuffer, 0, 2, SocketFlags.None, new AsyncCallback(BeginReceiveClientCallback), null);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
19
Source : Connection.cs
with GNU General Public License v3.0
from jo3bingham
with GNU General Public License v3.0
from jo3bingham
private void BeginReceiveWorldNameCallback(IAsyncResult ar)
{
try
{
if (_clientSocket == null)
{
return;
}
var count = _clientSocket.EndReceive(ar);
if (count <= 0)
{
ResetConnection();
return;
}
// The first message the client sends to the game server is the world name without a length.
// Read from the socket one byte at a time until the end of the string (\n) is read.
while (_clientInMessage.GetBuffer()[count - 1] != Convert.ToByte('\n'))
{
var read = _clientSocket.Receive(_clientInMessage.GetBuffer(), count, 1, SocketFlags.None);
if (read <= 0)
{
throw new Exception("[Connection.BeginReceiveWorldNameCallback] Client connection broken.");
}
count += read;
}
var worldName = Encoding.UTF8.GetString(_clientInMessage.GetBuffer(), 0, count - 1);
foreach (var world in _loginData.playdata.worlds)
{
var name = (string)world.name;
if (name.Equals(worldName, StringComparison.CurrentCultureIgnoreCase))
{
_clientSocket.BeginReceive(_clientInMessage.GetBuffer(), 0, 2, SocketFlags.None, new AsyncCallback(BeginReceiveClientCallback), 0);
_serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_serverSocket.Connect((string)world.externaladdressprotected, (int)world.externalportprotected);
_serverSocket.Send(_clientInMessage.GetBuffer(), 0, count, SocketFlags.None);
_serverSocket.BeginReceive(_serverInMessage.GetBuffer(), 0, 2, SocketFlags.None, new AsyncCallback(BeginReceiveServerCallback), 0);
return;
}
}
throw new Exception($"[Connection.BeginReceiveWorldNameCallback] Login data not found for world: {worldName}.");
}
catch (SocketException)
{
// This exception can happen if the client, forcefully, closes the connection (e.g., killing the client process).
ResetConnection();
}
catch (Exception ex)
{
_client.Logger.Error(ex.ToString());
_client.Logger.Error($"Data: {BitConverter.ToString(_clientInMessage.GetData()).Replace('-', ' ')}");
}
}
19
Source : BufferBinaryWriter.cs
with GNU General Public License v3.0
from krzys-h
with GNU General Public License v3.0
from krzys-h
public void Write(char[] value)
{
ResizeToFit((int)offset + value.Length);
foreach (char c in value)
buffer[offset++] = Convert.ToByte(c);
}
19
Source : CSharpExample.cs
with Mozilla Public License 2.0
from LibreHardwareMonitor
with Mozilla Public License 2.0
from LibreHardwareMonitor
private void Beep(uint freq)
{
if (m_bX64)
{
Out32_x64(0x43, 0xB6);
Out32_x64(0x42, (byte)(freq & 0xFF));
Out32_x64(0x42, (byte)(freq >> 9));
System.Threading.Thread.Sleep(10);
Out32_x64(0x61, (byte)(Convert.ToByte(Inp32_x64(0x61)) | 0x03));
}
else
{
Out32(0x43, 0xB6);
Out32(0x42, (byte)(freq & 0xFF));
Out32(0x42, (byte)(freq >> 9));
System.Threading.Thread.Sleep(10);
Out32(0x61, (byte)(Convert.ToByte(Inp32(0x61)) | 0x03));
}
}
19
Source : CSharpExample.cs
with Mozilla Public License 2.0
from LibreHardwareMonitor
with Mozilla Public License 2.0
from LibreHardwareMonitor
private void StopBeep()
{
if (m_bX64)
Out32_x64(0x61, (byte)(Convert.ToByte(Inp32_x64(0x61)) & 0xFC));
else
Out32(0x61, (byte)(Convert.ToByte(Inp32(0x61)) & 0xFC));
}
19
Source : CryptoHeaderPacker.cs
with Mozilla Public License 2.0
from martinstoeckli
with Mozilla Public License 2.0
from martinstoeckli
private static int IndexOfLastSeparator(byte[] packedCipher, int expectedSeparatorCount)
{
byte binarySeparator = Convert.ToByte(Separator);
int separatorCount = 0;
for (int index = 0; index < packedCipher.Length; index++)
{
if (binarySeparator == packedCipher[index])
separatorCount++;
if (separatorCount == expectedSeparatorCount)
return index;
}
return -1;
}
19
Source : CharExtensions.cs
with GNU General Public License v3.0
from ME3Tweaks
with GNU General Public License v3.0
from ME3Tweaks
public static byte ToByte(this char value)
{
return Convert.ToByte(value);
}
19
Source : Utils.cs
with MIT License
from med0x2e
with MIT License
from med0x2e
public static byte[] Encrypt(byte[] data, string encKey)
{
byte[] T = new byte[256];
byte[] S = new byte[256];
int keyLen = encKey.Length;
int dataLen = data.Length;
byte[] result = new byte[dataLen];
byte tmp;
int j = 0, t = 0, i = 0;
for (i = 0; i < 256; i++)
{
S[i] = Convert.ToByte(i);
T[i] = Convert.ToByte(encKey[i % keyLen]);
}
for (i = 0; i < 256; i++)
{
j = (j + S[i] + T[i]) % 256;
tmp = S[j];
S[j] = S[i];
S[i] = tmp;
}
j = 0;
for (int x = 0; x < dataLen; x++)
{
i = (i + 1) % 256;
j = (j + S[i]) % 256;
tmp = S[j];
S[j] = S[i];
S[i] = tmp;
t = (S[i] + S[j]) % 256;
result[x] = Convert.ToByte(data[x] ^ S[t]);
}
return result;
}
19
Source : Utils.cs
with MIT License
from med0x2e
with MIT License
from med0x2e
public static byte[] Decrypt(byte[] data, string encKey)
{
byte[] T = new byte[256];
byte[] S = new byte[256];
int keyLen = encKey.Length;
int dataLen = data.Length;
byte[] result = new byte[dataLen];
byte tmp;
int j = 0, t = 0, i = 0;
for (i = 0; i < 256; i++)
{
S[i] = Convert.ToByte(i);
T[i] = Convert.ToByte(encKey[i % keyLen]);
}
for (i = 0; i < 256; i++)
{
j = (j + S[i] + T[i]) % 256;
tmp = S[j];
S[j] = S[i];
S[i] = tmp;
}
j = 0;
for (int x = 0; x < dataLen; x++)
{
i = (i + 1) % 256;
j = (j + S[i]) % 256;
tmp = S[j];
S[j] = S[i];
S[i] = tmp;
t = (S[i] + S[j]) % 256;
result[x] = Convert.ToByte(data[x] ^ S[t]);
}
return result;
}
19
Source : ExcelHelperClass.cs
with MIT License
from michaelweber
with MIT License
from michaelweber
private static int GetColNumberFromExcelA1ColName(string colName)
{
if (colName.Length == 1)
{
return (int)Convert.ToByte(colName[0]) - (int)'A' + 1;
}
else
{
return ((int)Convert.ToByte(colName[0]) - (int)'A' + 1) * 26 +
((int)Convert.ToByte(colName[1]) - (int)'A' + 1);
}
}
19
Source : Ext.cs
with Apache License 2.0
from micro-chen
with Apache License 2.0
from micro-chen
public static bool EqualsAndSaveTo(int value, char c, List<byte> dest)
{
if (value < 0 || value > 255)
throw new ArgumentOutOfRangeException("value");
var b = (byte)value;
dest.Add(b);
return b == Convert.ToByte(c);
}
19
Source : SocketHelpers.cs
with MIT License
from microsoft
with MIT License
from microsoft
public static async Task<string> ReceiveLineAsync(this Socket socket, Encoding encoding = null)
{
var lineBytes = new List<byte>(1024);
var bytes = new byte[1];
while (true)
{
await socket.ReceiveBytesAsync(bytes, 0, 1).ConfigureAwait(false);
var lastIndex = lineBytes.Count - 1;
if ((lastIndex >= 0) && (lineBytes[lastIndex] == Convert.ToByte('\r')) && (bytes[0] == Convert.ToByte('\n')))
{
lineBytes.RemoveAt(lastIndex);
break;
}
lineBytes.Add(bytes[0]);
}
return (encoding ?? Encoding.UTF8).GetString(lineBytes.ToArray());
}
19
Source : WorkingDirectoryTests.cs
with MIT License
from microsoft
with MIT License
from microsoft
[TestCase, Order(3)]
public void RandomAccessReadWriteMemoryMappedProjectedFile()
{
string fileVirtualPath = this.Enlistment.GetVirtualPathTo("Test_EPF_WorkingDirectoryTests", "RandomAccessReadWriteMemoryMappedProjectedFile.cs");
string contents = fileVirtualPath.ShouldBeAFile(this.fileSystem).WithContents();
StringBuilder contentsBuilder = new StringBuilder(contents);
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fileVirtualPath))
{
// Length of the Byte-order-mark that will be at the start of the memory mapped file.
// See https://msdn.microsoft.com/en-us/library/windows/desktop/dd374101(v=vs.85).aspx
int bomOffset = 3;
// offset -> Number of bytes from the start of the file where the view starts
int offset = 64;
int size = contents.Length;
string newContent = "**NEWCONTENT**";
using (MemoryMappedViewAccessor randomAccessor = mmf.CreateViewAccessor(offset, size - offset + bomOffset))
{
randomAccessor.CanRead.ShouldEqual(true);
randomAccessor.CanWrite.ShouldEqual(true);
for (int i = 0; i < size - offset; ++i)
{
((char)randomAccessor.ReadByte(i)).ShouldEqual(contents[i + offset - bomOffset]);
}
for (int i = 0; i < newContent.Length; ++i)
{
// Convert to byte before writing rather than writing as char, because char version will write a 16-bit
// unicode char
randomAccessor.Write(i, Convert.ToByte(newContent[i]));
((char)randomAccessor.ReadByte(i)).ShouldEqual(newContent[i]);
}
for (int i = 0; i < newContent.Length; ++i)
{
contentsBuilder[offset + i - bomOffset] = newContent[i];
}
contents = contentsBuilder.ToString();
}
// Verify the file has the new contents inserted into it
using (MemoryMappedViewAccessor randomAccessor = mmf.CreateViewAccessor(offset: 0, size: size + bomOffset))
{
for (int i = 0; i < size; ++i)
{
((char)randomAccessor.ReadByte(i + bomOffset)).ShouldEqual(contents[i]);
}
}
}
// Confirm the new contents was written to disk
fileVirtualPath.ShouldBeAFile(this.fileSystem).WithContents(contents);
}
19
Source : WorkingDirectoryTests.cs
with MIT License
from microsoft
with MIT License
from microsoft
[TestCase, Order(4)]
public void StreamAndRandomAccessReadWriteMemoryMappedProjectedFile()
{
string fileVirtualPath = this.Enlistment.GetVirtualPathTo("Test_EPF_WorkingDirectoryTests", "StreamAndRandomAccessReadWriteMemoryMappedProjectedFile.cs");
StringBuilder contentsBuilder = new StringBuilder();
// Length of the Byte-order-mark that will be at the start of the memory mapped file.
// See https://msdn.microsoft.com/en-us/library/windows/desktop/dd374101(v=vs.85).aspx
int bomOffset = 3;
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fileVirtualPath))
{
// The text length of StreamAndRandomAccessReadWriteMemoryMappedProjectedFile.cs was determined
// outside of this test so that the test would not hydrate the file before we access via MemoryMappedFile
int fileTextLength = 13762;
int size = bomOffset + fileTextLength;
int streamAccessWriteOffset = 64;
int randomAccessWriteOffset = 128;
string newStreamAccessContent = "**NEW_STREAM_CONTENT**";
string newRandomAccessConents = "&&NEW_RANDOM_CONTENT&&";
// Read (and modify) contents using stream accessor
using (MemoryMappedViewStream streamAccessor = mmf.CreateViewStream(offset: 0, size: size))
{
streamAccessor.CanRead.ShouldEqual(true);
streamAccessor.CanWrite.ShouldEqual(true);
for (int i = 0; i < size; ++i)
{
contentsBuilder.Append((char)streamAccessor.ReadByte());
}
// Reset to the start of the stream (which will place the streamAccessor at offset in the memory file)
streamAccessor.Seek(streamAccessWriteOffset, SeekOrigin.Begin);
byte[] newContentBuffer = Encoding.ASCII.GetBytes(newStreamAccessContent);
streamAccessor.Write(newContentBuffer, 0, newStreamAccessContent.Length);
for (int i = 0; i < newStreamAccessContent.Length; ++i)
{
contentsBuilder[streamAccessWriteOffset + i] = newStreamAccessContent[i];
}
}
// Read (and modify) contents using random accessor
using (MemoryMappedViewAccessor randomAccessor = mmf.CreateViewAccessor(offset: 0, size: size))
{
randomAccessor.CanRead.ShouldEqual(true);
randomAccessor.CanWrite.ShouldEqual(true);
// Confirm the random accessor reads the same content that was read (and written) by the stream
// accessor
for (int i = 0; i < size; ++i)
{
((char)randomAccessor.ReadByte(i)).ShouldEqual(contentsBuilder[i]);
}
// Write some new content
for (int i = 0; i < newRandomAccessConents.Length; ++i)
{
// Convert to byte before writing rather than writing as char, because char version will write a 16-bit
// unicode char
randomAccessor.Write(i + randomAccessWriteOffset, Convert.ToByte(newRandomAccessConents[i]));
((char)randomAccessor.ReadByte(i + randomAccessWriteOffset)).ShouldEqual(newRandomAccessConents[i]);
}
for (int i = 0; i < newRandomAccessConents.Length; ++i)
{
contentsBuilder[randomAccessWriteOffset + i] = newRandomAccessConents[i];
}
}
// Verify the file one more time with a stream accessor
using (MemoryMappedViewStream streamAccessor = mmf.CreateViewStream(offset: 0, size: size))
{
for (int i = 0; i < size; ++i)
{
streamAccessor.ReadByte().ShouldEqual(contentsBuilder[i]);
}
}
}
// Remove the BOM before comparing with the contents of the file on disk
contentsBuilder.Remove(0, bomOffset);
// Confirm the new contents was written to the file
fileVirtualPath.ShouldBeAFile(this.fileSystem).WithContents(contentsBuilder.ToString());
}
19
Source : Plist.cs
with MIT License
from newky2k
with MIT License
from newky2k
private static byte[] writeBinaryString(string value, bool head)
{
List<byte> nums = new List<byte>();
List<byte> nums1 = new List<byte>();
char[] charArray = value.ToCharArray();
for (int i = 0; i < (int)charArray.Length; i++)
{
nums.Add(Convert.ToByte(charArray[i]));
}
if (head)
{
if (value.Length >= 15)
{
nums1.Add(95);
nums1.AddRange(Plist.writeBinaryInteger(nums.Count, false));
}
else
{
nums1.Add(Convert.ToByte(80 | Convert.ToByte(value.Length)));
}
}
nums.InsertRange(0, nums1);
Plist.objectTable.InsertRange(0, nums);
return nums.ToArray();
}
19
Source : BinaryGeneral.cs
with MIT License
from NewLifeX
with MIT License
from NewLifeX
public virtual void Write(Char ch) { Write(Convert.ToByte(ch)); }
19
Source : Reader.DialogPanel.cs
with MIT License
from NightlyRevenger
with MIT License
from NightlyRevenger
public static ChatLogItem GetCutsceneText()
{
ChatLogItem result = new ChatLogItem();
if (!CanGetCutScene() || !MemoryHandler.Instance.IsAttached)
{
return result;
}
Int16 chatCode = 0x0044;
byte colonBytes = Convert.ToByte(':');
byte dotBytes = Convert.ToByte('.');
byte spaceBytes = Convert.ToByte(' ');
byte[] chatCodeBytes = BitConverter.GetBytes(chatCode);
try
{
var cutsceneTextPointer1 = (IntPtr)Scanner.Instance.Locations[Signatures.CutsceneText1];
var cutsceneTextLengthPointer = (IntPtr)Scanner.Instance.Locations[Signatures.CutsceneTextLength];
var cutsceneDetector = (IntPtr)Scanner.Instance.Locations[Signatures.CutsceneDetector];
int textLength = (int)MemoryHandler.Instance.GetPlatformInt(cutsceneTextLengthPointer);
int isCutscene = (int)MemoryHandler.Instance.GetPlatformInt(cutsceneDetector);
if (textLength < 2 || isCutscene == 1)
return result;
byte[] cutsceneBytesRaw1 = MemoryHandler.Instance.GetByteArray(cutsceneTextPointer1, 256);
int textEnd1 = GetRealTextLength(ref cutsceneBytesRaw1);
if (textEnd1 > 2)
{
byte[] cutsceneBytes1 = cutsceneBytesRaw1;
Int32 unixTimestamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
byte[] unixTimestampBytes = BitConverter.GetBytes(unixTimestamp).ToArray();
byte[] npcNameBytes = new byte[3];
npcNameBytes[0] = dotBytes;
npcNameBytes[1] = dotBytes;
npcNameBytes[2] = dotBytes;
List<byte> rawBytesList = new List<byte>(unixTimestampBytes.Length + chatCodeBytes.Length + 1 +
npcNameBytes.Length + 1 + cutsceneBytes1.Length);
rawBytesList.AddRange(unixTimestampBytes);
rawBytesList.AddRange(chatCodeBytes);
rawBytesList.AddRange(new Byte[] { 0x00, 0x00 });
rawBytesList.Add(colonBytes);
rawBytesList.AddRange(npcNameBytes);
rawBytesList.Add(colonBytes);
rawBytesList.AddRange(cutsceneBytes1);
ChatLogItem chatLogItem = ChatEntry.Process(rawBytesList.ToArray());
if (textEnd1 > 2)
{
String onlyLettersLine = new String(chatLogItem.Line.Where(Char.IsLetter).ToArray());
if (onlyLettersLine.Length > chatLogItem.Line.Length / GlobalSettings.LineLettersCoefficient)
result = chatLogItem;
}
}
if (result?.Line != null)
{
if (result.Line.Contains("]") && result.Line.Contains("["))
return new ChatLogItem();
}
}
catch (Exception)
{
result = new ChatLogItem();
}
return result;
}
19
Source : ChatCleaner.cs
with MIT License
from NightlyRevenger
with MIT License
from NightlyRevenger
public static string ProcessFullLine(string code, byte[] bytes)
{
var line = HttpUtility.HtmlDecode(Encoding.UTF8.GetString(bytes.ToArray())).Replace(" ", " ");
try
{
List<byte> autoTranslateList = new List<byte>(bytes.Length);
List<byte> newList = new List<byte>();
for (var x = 0; x < bytes.Count(); x++)
{
switch (bytes[x])
{
case 2:
// special in-game replacements/wrappers
// 2 46 5 7 242 2 210 3
// 2 29 1 3
// remove them
var length = bytes[x + 2];
var limit = length - 1;
if (length > 1)
{
x = x + 3 ;
autoTranslateList.Add(Convert.ToByte('['));
byte[] translated = new byte[limit];
Buffer.BlockCopy(bytes, x, translated, 0, limit);
foreach (var b in translated)
{
autoTranslateList.AddRange(Encoding.UTF8.GetBytes(b.ToString("X2")));
}
autoTranslateList.Add(Convert.ToByte(']'));
var bCheckStr = Encoding.UTF8.GetString(autoTranslateList.ToArray());
if (bCheckStr != null && bCheckStr.Length > 0)
{
if (bCheckStr.Equals("[59]"))
{
newList.Add(0x40);
}
if (Utilities.AutoTranslate.EnDict.TryGetValue(bCheckStr.Replace("[0", "[").ToLower(), out var AutoTranslateVal))
{
newList.AddRange(Encoding.UTF8.GetBytes(AutoTranslateVal));
}
}
autoTranslateList.Clear();
x += limit;
}
else
{
x = x + 4;
newList.Add(32);
newList.Add(bytes[x]);
}
break;
// unit separator
case 31:
// TODO: this breaks in some areas like NOVICE chat
// if (PlayerChatCodesRegex.IsMatch(code)) {
// newList.Add(58);
// }
// else {
// newList.Add(31);
// }
newList.Add(58);
if (PlayerChatCodesRegex.IsMatch(code))
{
newList.Add(32);
}
break;
default:
newList.Add(bytes[x]);
break;
}
}
var cleaned = HttpUtility.HtmlDecode(Encoding.UTF8.GetString(newList.ToArray())).Replace(" ", " ");
newList.Clear();
// replace right arrow in chat (parsing)
cleaned = ArrowRegex.Replace(cleaned, "⇒");
// replace HQ symbol
cleaned = HQRegex.Replace(cleaned, "[HQ]");
// replace all Extended special purpose unicode with empty string
cleaned = SpecialPurposeUnicodeRegex.Replace(cleaned, string.Empty);
// cleanup special replacement character bytes: 239 191 189
cleaned = SpecialReplacementRegex.Replace(cleaned, string.Empty);
// remove new lines
cleaned = NewLineRegex.Replace(cleaned, string.Empty);
// remove characters 0-31
cleaned = NoPrintingCharactersRegex.Replace(cleaned, string.Empty);
line = cleaned;
}
catch (Exception ex)
{
MemoryHandler.Instance.RaiseException(Logger, ex, true);
}
return ProcessName(line);
}
19
Source : Reader.DialogPanel.cs
with MIT License
from NightlyRevenger
with MIT License
from NightlyRevenger
public static ChatLogItem GetDialogPanel()
{
var result = new ChatLogItem();
if (!CanGetDialogPanel() || !MemoryHandler.Instance.IsAttached)
{
return result;
}
Int16 chatCode = 0x003d;
byte colonBytes = Convert.ToByte(':');
byte[] chatCodeBytes = BitConverter.GetBytes(chatCode);
var dialogPanelNamePointer = (IntPtr)Scanner.Instance.Locations[Signatures.DialogPanelName];
var dialogPanelNameLengthPointer = IntPtr.Subtract(dialogPanelNamePointer, MemoryHandler.Instance.Structures.DialogPanelPointers.LengtsOffset);
var dialogPanelTextPointer = (IntPtr)Scanner.Instance.Locations[Signatures.DialogPanelText];
var dialogPanelText = new IntPtr(MemoryHandler.Instance.GetPlatformUInt(dialogPanelTextPointer));
var dialogPanelTextLegthPointer = IntPtr.Add(dialogPanelTextPointer, MemoryHandler.Instance.Structures.DialogPanelPointers.TextLengthOffset);
int nameLength = (int)MemoryHandler.Instance.GetPlatformInt(dialogPanelNameLengthPointer);
int textLength = (int)MemoryHandler.Instance.GetPlatformInt(dialogPanelTextLegthPointer);
if (textLength > 1 && nameLength > 1)
{
if (textLength > 512)
textLength = 512;
if (nameLength > 128)
nameLength = 128;
byte[] npcNameBytes = MemoryHandler.Instance.GetByteArray(dialogPanelNamePointer, nameLength);
byte[] textBytes = MemoryHandler.Instance.GetByteArray(dialogPanelText, textLength);
nameLength = GetRealTextLength(ref npcNameBytes);
textLength = GetRealTextLength(ref textBytes);
Int32 unixTimestamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
byte[] unixTimestampBytes = BitConverter.GetBytes(unixTimestamp).ToArray();
List<byte> rawBytesList = new List<byte>(unixTimestampBytes.Length + chatCodeBytes.Length + 1 +
npcNameBytes.Length + 1 + textBytes.Length);
rawBytesList.AddRange(unixTimestampBytes);
rawBytesList.AddRange(chatCodeBytes);
rawBytesList.AddRange(new Byte[] { 0x00, 0x00 });
rawBytesList.Add(colonBytes);
rawBytesList.AddRange(npcNameBytes);
rawBytesList.Add(colonBytes);
rawBytesList.AddRange(textBytes);
ChatLogItem chatLogItem = ChatEntry.Process(rawBytesList.ToArray());
String onlyLettersLine = new String(chatLogItem.Line.Where(Char.IsLetter).ToArray());
if (onlyLettersLine.Length > chatLogItem.Line.Length / GlobalSettings.LineLettersCoefficient)
result = chatLogItem;
}
return result;
}
19
Source : RegisterFunctions.cs
with MIT License
from NModbus
with MIT License
from NModbus
public static byte[][] CharsToByteValueArrays(char[] data, uint wordSize, bool frontPadding = true, bool singleCharPerRegister = true)
{
var bytesPerWord = RegisterFunctions.GetRegisterMultiplier(wordSize) * 2;
if (!singleCharPerRegister)
{
var remainder = data.Length % bytesPerWord;
var registerBytes = remainder > 0
? data.Length + (bytesPerWord - remainder)
: data.Length;
var byteArray = new byte[registerBytes];
for (var index = 0; index < byteArray.Length; index++)
{
byteArray[index] = index < data.Length
? Convert.ToByte(data[index])
: Convert.ToByte('\0'); //Unicode Null Charector
}
var byteValueArrays = new byte[byteArray.Length / bytesPerWord][];
for (var index = 0; index < byteValueArrays.Length; index++)
{
var offset = index * bytesPerWord;
byteValueArrays[index] = new ArraySegment<byte>(byteArray, offset, bytesPerWord).ToArray();
}
return byteValueArrays;
}
return (frontPadding)
? data.Select(e =>
{
var bytes = new byte[bytesPerWord];
bytes[bytes.Length - 1] = Convert.ToByte(e);
return bytes;
}).ToArray()
: data.Select(e =>
{
var bytes = new byte[bytesPerWord];
bytes[0] = Convert.ToByte(e);
return bytes;
}).ToArray();
}
19
Source : AuthControllerTests.cs
with GNU General Public License v3.0
from NosCoreIO
with GNU General Public License v3.0
from NosCoreIO
[TestMethod]
public void GetExpectingConnectionReturnAccountNameWhenAuthCode()
{
SessionFactory.Instance.AuthCodes[_tokenGuid] = _session.Account.Name;
var result = _controller.GetExpectingConnection(_session.Account.Name, string.Join("", _tokenGuid.ToCharArray().Select(s => Convert.ToByte(s).ToString("x"))), 1);
replacedert.AreEqual(_session.Account.Name, ((OkObjectResult)result).Value);
}
See More Examples