Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Text;
- using System.Text.RegularExpressions;
- namespace CipherTest
- {
- // Thanks to Nathan Moinvaziri on stackoverflow for the original byte <-> hex code transformers! https://stackoverflow.com/a/5919521
- static class Helpers
- {
- static readonly Regex ValidRegex = new Regex(@"^[\x20-\xFF]+$", RegexOptions.Compiled);
- static readonly Regex HexRegex = new Regex("^[0-9A-Fa-f]+$", RegexOptions.Compiled);
- static readonly string HexAlphabet = "0123456789ABCDEF";
- static readonly int[] HexValue = new int[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F };
- public static ulong RL(this ulong x, int n) => (x << n) | (x >> (64 - n));
- public static bool IsValidString(string str) => ValidRegex.IsMatch(str);
- public static bool IsHexString(string str) => HexRegex.IsMatch(str);
- public static string BytesToHex(byte[] bytes)
- {
- StringBuilder result = new StringBuilder(bytes.Length * 2);
- foreach (byte b in bytes)
- {
- result.Append(HexAlphabet[(int)(b >> 4)]);
- result.Append(HexAlphabet[(int)(b & 0xF)]);
- }
- return result.ToString();
- }
- public static byte[] HexToBytes(string hex)
- {
- if ((hex.Length & 1) == 1 || !IsHexString(hex))
- {
- return null;
- }
- byte[] bytes = new byte[hex.Length / 2];
- for (int x = 0, i = 0; i < hex.Length; i += 2, x += 1)
- {
- bytes[x] = (byte) (HexValue[Char.ToUpper(hex[i + 0]) - '0'] << 4 | HexValue[Char.ToUpper(hex[i + 1]) - '0']);
- }
- return bytes;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement