// 程序员计算器 - 绿色工具箱 // C# 5.0 语法,零依赖。二进制/八进制/十进制/十六进制实时互转 + 位运算 + 64 位点选 using System; using System.Collections.Generic; using System.Drawing; using System.Globalization; using System.Text; using System.Windows.Forms; namespace GreenToolbox { // ===== 纯函数区(可自测) ===== public static class CalcOps { public static int DigitValue(char c) { if (c >= '0' && c <= '9') return c - '0'; if (c >= 'a' && c <= 'f') return c - 'a' + 10; if (c >= 'A' && c <= 'F') return c - 'A' + 10; return -1; } // 解析:允许空格和下划线分组、允许 0x/0b/0o 前缀(前缀会覆盖当前进制)、 // 十进制可带负号。返回 false 时 err 里写原因,界面上直接显示给用户 public static bool Parse(string text, int radix, out long value, out string err) { value = 0; err = ""; if (text == null) { err = "没有输入"; return false; } string s = text.Trim().Replace(" ", "").Replace("_", "").Replace(",", ""); if (s.Length == 0) { err = "没有输入"; return false; } bool neg = false; if (s[0] == '-') { neg = true; s = s.Substring(1); } else if (s[0] == '+') { s = s.Substring(1); } if (s.Length == 0) { err = "只有一个符号"; return false; } int baseUsed = radix; if (s.Length > 2 && s[0] == '0') { char p = char.ToLowerInvariant(s[1]); if (p == 'x') { baseUsed = 16; s = s.Substring(2); } else if (p == 'b') { baseUsed = 2; s = s.Substring(2); } else if (p == 'o') { baseUsed = 8; s = s.Substring(2); } } if (s.Length == 0) { err = "前缀后面没有数字"; return false; } if (neg && baseUsed != 10) { err = "只有十进制能输入负数"; return false; } ulong acc = 0; for (int i = 0; i < s.Length; i++) { int d = DigitValue(s[i]); if (d < 0 || d >= baseUsed) { err = "「" + s[i] + "」不是 " + RadixName(baseUsed) + " 里的数字"; return false; } ulong nb = acc * (ulong)baseUsed + (ulong)d; // 无符号 64 位溢出会让结果回绕,必须提前拦住 if (acc > (ulong.MaxValue - (ulong)d) / (ulong)baseUsed) { err = "超出 64 位范围"; return false; } acc = nb; } if (neg) { if (acc > 9223372036854775808UL) { err = "负数超出 64 位范围"; return false; } if (acc == 9223372036854775808UL) { value = long.MinValue; return true; } value = -(long)acc; return true; } value = unchecked((long)acc); return true; } public static string RadixName(int radix) { if (radix == 2) return "二进制"; if (radix == 8) return "八进制"; if (radix == 16) return "十六进制"; return "十进制"; } public static string FormatHex(long v) { if (v == 0) return "0x0"; return "0x" + ((ulong)v).ToString("X", CultureInfo.InvariantCulture); } // 负数要按 64 位补码显示(0xFFFFFFFFFFFFFFFF 这类),不能带负号。 // Convert.ToString(long, 2/8) 对负数输出「负号 + 绝对值」,必须自己按无符号转 private static string ToRadix(ulong u, int radix) { if (u == 0) return "0"; char[] digits = "01234567".ToCharArray(); if (radix == 2) digits = "01".ToCharArray(); else if (radix == 16) digits = "0123456789ABCDEF".ToCharArray(); StringBuilder sb = new StringBuilder(); while (u > 0) { sb.Insert(0, digits[(int)(u % (ulong)radix)]); u /= (ulong)radix; } return sb.ToString(); } public static string FormatOct(long v) { return "0o" + ToRadix(unchecked((ulong)v), 8); } public static string FormatBin(long v) { // 4 位一组,肉眼数位数不累 string raw = ToRadix(unchecked((ulong)v), 2); StringBuilder sb = new StringBuilder(); int pad = (4 - raw.Length % 4) % 4; for (int i = 0; i < pad; i++) raw = "0" + raw; for (int i = 0; i < raw.Length; i++) { if (i > 0 && i % 4 == 0) sb.Append(' '); sb.Append(raw[i]); } return sb.ToString(); } public static string FormatDecSigned(long v) { return v.ToString(CultureInfo.InvariantCulture); } public static string FormatDecUnsigned(long v) { return unchecked((ulong)v).ToString(CultureInfo.InvariantCulture); } // 位运算 public static long And(long a, long b) { return a & b; } public static long Or(long a, long b) { return a | b; } public static long Xor(long a, long b) { return a ^ b; } public static long Not(long a) { return ~a; } // 左移按无符号做:移出的位直接丢,和 C 的 uint64 行为一致 public static long Shl(long a, int n) { if (n < 0) n = -n; n = n & 63; return unchecked((long)((ulong)a << n)); } // 逻辑右移(高位补 0)。程序员计算器里按位看更常见,别用算术右移 public static long ShrLogical(long a, int n) { if (n < 0) n = -n; n = n & 63; return unchecked((long)((ulong)a >> n)); } public static int ShiftCount(long n) { int k = (int)n; return k & 63; } public static bool BitAt(long v, int index) { if (index < 0 || index > 63) return false; return ((ulong)v >> index & 1UL) == 1UL; } public static long SetBit(long v, int index, bool on) { if (index < 0 || index > 63) return v; ulong mask = 1UL << index; if (on) return unchecked((long)((ulong)v | mask)); return unchecked((long)((ulong)v & ~mask)); } // 大端字节序:0x0102... 显示成 01 02 ...,跟抓包/内存看图习惯一致 public static string ByteView(long v) { ulong u = unchecked((ulong)v); StringBuilder sb = new StringBuilder(); for (int i = 7; i >= 0; i--) { if (sb.Length > 0) sb.Append(' '); sb.Append(((byte)((u >> (i * 8)) & 0xFF)).ToString("X2", CultureInfo.InvariantCulture)); } return sb.ToString(); } // 能显示的 ASCII 才显示,其余打点,避免界面出现控制字符 public static string AsciiView(long v) { ulong u = unchecked((ulong)v); StringBuilder sb = new StringBuilder(); for (int i = 7; i >= 0; i--) { byte b = (byte)((u >> (i * 8)) & 0xFF); if (b >= 32 && b <= 126) sb.Append((char)b); else sb.Append('.'); } return sb.ToString(); } public static string PopCountText(long v) { ulong u = unchecked((ulong)v); int n = 0; while (u != 0) { u &= (u - 1); n++; } return n + " 位为 1"; } } public class DevCalcForm : Form { private static readonly Color COL_GREEN = Color.FromArgb(0, 145, 88); private static readonly Color COL_PANEL = Color.FromArgb(245, 249, 246); private static readonly Color COL_GRAY = Color.FromArgb(120, 130, 124); private static readonly Color COL_LINE = Color.FromArgb(224, 230, 226); private TextBox txtInput; private ComboBox cmbRadix; private Label lblDec, lblUnsigned, lblHex, lblOct, lblBin, lblBytes, lblAscii, lblBits, lblError; private TextBox txtOperand; private CheckBox[] bits = new CheckBox[64]; private long _value; private bool _syncing; public DevCalcForm() { InitUi(); SetValue(255); _syncing = true; txtInput.Text = "255"; _syncing = false; } private void InitUi() { this.Text = "程序员计算器 - 绿色工具箱"; this.Font = new Font("Microsoft YaHei UI", 9.5f); this.BackColor = Color.White; this.ForeColor = Color.FromArgb(34, 40, 36); this.ClientSize = new Size(680, 620); this.MinimumSize = new Size(620, 580); this.StartPosition = FormStartPosition.CenterScreen; int x = 18, y = 14; Label l0 = new Label(); l0.Text = "进制互转 + 位运算 + 64 位点选。输入支持 0x / 0b / 0o 前缀和空格分组。"; l0.AutoSize = true; l0.ForeColor = COL_GRAY; l0.Location = new Point(x, y); this.Controls.Add(l0); y += 30; txtInput = new TextBox(); txtInput.Location = new Point(x, y); txtInput.Size = new Size(420, 30); txtInput.Font = new Font("Consolas", 13f); txtInput.TextChanged += new EventHandler(InputChanged); this.Controls.Add(txtInput); cmbRadix = new ComboBox(); cmbRadix.DropDownStyle = ComboBoxStyle.DropDownList; cmbRadix.Items.Add("十进制"); cmbRadix.Items.Add("十六进制"); cmbRadix.Items.Add("二进制"); cmbRadix.Items.Add("八进制"); cmbRadix.SelectedIndex = 0; cmbRadix.Location = new Point(x + 430, y + 1); cmbRadix.Size = new Size(110, 26); cmbRadix.SelectedIndexChanged += new EventHandler(InputChanged); this.Controls.Add(cmbRadix); y += 40; lblError = new Label(); lblError.Text = ""; lblError.AutoSize = true; lblError.ForeColor = Color.FromArgb(190, 70, 60); lblError.Location = new Point(x, y); this.Controls.Add(lblError); y += 24; lblDec = AddRow("有符号十进制", ref y, x); lblUnsigned = AddRow("无符号十进制", ref y, x); lblHex = AddRow("十六进制", ref y, x); lblOct = AddRow("八进制", ref y, x); lblBin = AddRow("二进制", ref y, x); lblBytes = AddRow("字节(大端)", ref y, x); lblAscii = AddRow("ASCII", ref y, x); y += 4; Label l1 = new Label(); l1.Text = "位运算(第二个数用当前进制输入)"; l1.AutoSize = true; l1.ForeColor = COL_GRAY; l1.Location = new Point(x, y); this.Controls.Add(l1); y += 26; txtOperand = new TextBox(); txtOperand.Location = new Point(x, y); txtOperand.Size = new Size(140, 26); txtOperand.Font = new Font("Consolas", 11f); txtOperand.Text = "0"; this.Controls.Add(txtOperand); string[] ops = new string[] { "AND", "OR", "XOR", "NOT", "<<", ">>" }; for (int i = 0; i < ops.Length; i++) { Button b = new Button(); b.Text = ops[i]; b.Location = new Point(x + 150 + i * 66, y - 2); b.Size = new Size(60, 28); b.FlatStyle = FlatStyle.Flat; b.FlatAppearance.BorderColor = COL_LINE; b.ForeColor = Color.FromArgb(60, 68, 64); b.Tag = ops[i]; b.Click += new EventHandler(OpClick); this.Controls.Add(b); } y += 38; Label l2 = new Label(); l2.Text = "点选二进制位(第 63 位在左上,第 0 位在右下)"; l2.AutoSize = true; l2.ForeColor = COL_GRAY; l2.Location = new Point(x, y); this.Controls.Add(l2); y += 24; // 64 个勾选框,8 行 × 8 列,从高位往低位排 for (int row = 0; row < 8; row++) { for (int col = 0; col < 8; col++) { int index = 63 - (row * 8 + col); CheckBox cb = new CheckBox(); cb.Text = index.ToString(CultureInfo.InvariantCulture); cb.AutoSize = false; cb.Size = new Size(76, 22); cb.Location = new Point(x + col * 80, y + row * 24); cb.ForeColor = Color.FromArgb(60, 68, 64); cb.Tag = index; cb.CheckedChanged += new EventHandler(BitChanged); this.Controls.Add(cb); bits[index] = cb; } } y += 8 * 24 + 4; lblBits = new Label(); lblBits.Text = ""; lblBits.AutoSize = true; lblBits.ForeColor = COL_GREEN; lblBits.Location = new Point(x, y); this.Controls.Add(lblBits); } private Label AddRow(string name, ref int y, int x) { Label lb = new Label(); lb.Text = name; lb.AutoSize = false; lb.Size = new Size(110, 24); lb.ForeColor = COL_GRAY; lb.Location = new Point(x, y + 3); this.Controls.Add(lb); Label val = new Label(); val.Text = ""; val.AutoSize = false; val.Size = new Size(520, 24); val.Font = new Font("Consolas", 10.5f); val.TextAlign = ContentAlignment.MiddleLeft; val.Location = new Point(x + 116, y + 2); val.Cursor = Cursors.Hand; val.Click += delegate { if (val.Text.Length == 0) return; try { Clipboard.SetText(val.Text); val.ForeColor = COL_GREEN; } catch { } }; this.Controls.Add(val); y += 28; return val; } private int CurrentRadix() { if (cmbRadix.SelectedIndex == 1) return 16; if (cmbRadix.SelectedIndex == 2) return 2; if (cmbRadix.SelectedIndex == 3) return 8; return 10; } private void InputChanged(object sender, EventArgs e) { if (_syncing) return; long v; string err; if (!CalcOps.Parse(txtInput.Text, CurrentRadix(), out v, out err)) { lblError.Text = err; return; } lblError.Text = ""; SetValue(v); } private void SetValue(long v) { _value = v; lblDec.Text = CalcOps.FormatDecSigned(v); lblUnsigned.Text = CalcOps.FormatDecUnsigned(v); lblHex.Text = CalcOps.FormatHex(v); lblOct.Text = CalcOps.FormatOct(v); lblBin.Text = CalcOps.FormatBin(v); lblBytes.Text = CalcOps.ByteView(v); lblAscii.Text = CalcOps.AsciiView(v); lblBits.Text = CalcOps.PopCountText(v); _syncing = true; try { for (int i = 0; i < 64; i++) bits[i].Checked = CalcOps.BitAt(v, i); } finally { _syncing = false; } } private void BitChanged(object sender, EventArgs e) { if (_syncing) return; CheckBox cb = sender as CheckBox; if (cb == null) return; int index = (int)cb.Tag; SetValue(CalcOps.SetBit(_value, index, cb.Checked)); _syncing = true; try { txtInput.Text = FormatForInput(_value); } finally { _syncing = false; } lblError.Text = ""; } private string FormatForInput(long v) { int radix = CurrentRadix(); if (radix == 16) return CalcOps.FormatHex(v); if (radix == 2) return CalcOps.FormatBin(v).Replace(" ", ""); if (radix == 8) return CalcOps.FormatOct(v); return CalcOps.FormatDecSigned(v); } private void OpClick(object sender, EventArgs e) { Button b = sender as Button; if (b == null) return; string op = (string)b.Tag; long n = _value; long other = 0; string err; if (op != "NOT" && op != "<<" && op != ">>") { if (!CalcOps.Parse(txtOperand.Text, CurrentRadix(), out other, out err)) { lblError.Text = "第二个数无效:" + err; return; } } else if (op == "<<" || op == ">>") { long cnt; if (!CalcOps.Parse(txtOperand.Text, CurrentRadix(), out cnt, out err)) { lblError.Text = "移动位数无效:" + err; return; } other = cnt; } long r = n; if (op == "AND") r = CalcOps.And(n, other); else if (op == "OR") r = CalcOps.Or(n, other); else if (op == "XOR") r = CalcOps.Xor(n, other); else if (op == "NOT") r = CalcOps.Not(n); else if (op == "<<") r = CalcOps.Shl(n, CalcOps.ShiftCount(other)); else if (op == ">>") r = CalcOps.ShrLogical(n, CalcOps.ShiftCount(other)); SetValue(r); _syncing = true; try { txtInput.Text = FormatForInput(r); } finally { _syncing = false; } lblError.Text = ""; } } public static class CalcSelfTest { private static int _pass = 0; private static int _fail = 0; private static List _lines = new List(); private static string Esc(string s) { if (s == null) return ""; return s.Replace("\r", "\\r").Replace("\n", "\\n"); } private static void Check(string name, string got, string want) { if (got == null) got = ""; if (want == null) want = ""; if (got == want) { _pass++; _lines.Add(" [ok] " + name); } else { _fail++; _lines.Add(" [!!] " + name + " 期望[" + Esc(want) + "] 实际[" + Esc(got) + "]"); } } private static void CheckTrue(string name, bool ok, string detail) { Check(name, ok ? "yes" : "no", "yes"); if (!ok && detail != null) _lines.Add(" 详情:" + Esc(detail)); } private static string P(string text, int radix) { long v; string err; if (!CalcOps.Parse(text, radix, out v, out err)) return "ERR:" + err; return v.ToString(CultureInfo.InvariantCulture); } public static int Run(string dir) { try { _lines.Add("程序员计算器 自测"); // ── 解析:各进制 ── Check("十进制 255", P("255", 10), "255"); Check("十六进制 FF", P("FF", 16), "255"); Check("二进制 11111111", P("11111111", 2), "255"); Check("八进制 777", P("777", 8), "511"); Check("0x 前缀覆盖当前进制", P("0xFF", 10), "255"); Check("0b 前缀", P("0b1010", 10), "10"); Check("0o 前缀", P("0o17", 10), "15"); Check("小写十六进制也认", P("ff", 16), "255"); Check("下划线分组", P("1_000_000", 10), "1000000"); Check("空格分组", P("1111 0000", 2), "240"); Check("十进制负数", P("-255", 10), "-255"); Check("加号也接受", P("+42", 10), "42"); Check("前导零不当作八进制", P("010", 10), "10"); Check("0 就是 0", P("0", 10), "0"); // ── 解析:错误路径必须说人话 ── CheckTrue("空串报错", P("", 10).StartsWith("ERR:没有输入"), P("", 10)); CheckTrue("只有负号报错", P("-", 10).StartsWith("ERR:"), P("-", 10)); CheckTrue("十六进制里出现 G 报错", P("1G", 16).StartsWith("ERR:"), P("1G", 16)); CheckTrue("二进制里出现 2 报错", P("102", 2).StartsWith("ERR:"), P("102", 2)); CheckTrue("十六进制不能带负号", P("-FF", 16).StartsWith("ERR:"), P("-FF", 16)); CheckTrue("0x 后面没数字报错", P("0x", 10).StartsWith("ERR:"), P("0x", 10)); CheckTrue("超 64 位报错", P("1FFFFFFFFFFFFFFFF", 16).StartsWith("ERR:超出"), P("1FFFFFFFFFFFFFFFF", 16)); Check("FFFFFFFFFFFFFFFF = -1(补码)", P("FFFFFFFFFFFFFFFF", 16), "-1"); Check("最大的 long", P("7FFFFFFFFFFFFFFF", 16), "9223372036854775807"); // ── 格式化 ── Check("十六进制 255", CalcOps.FormatHex(255), "0xFF"); Check("十六进制 0", CalcOps.FormatHex(0), "0x0"); Check("十六进制 -1 显示全 F", CalcOps.FormatHex(-1), "0xFFFFFFFFFFFFFFFF"); Check("八进制 8", CalcOps.FormatOct(8), "0o10"); Check("二进制 5 补足 4 位", CalcOps.FormatBin(5), "0101"); Check("二进制按 4 位分组", CalcOps.FormatBin(255), "1111 1111"); Check("二进制 0", CalcOps.FormatBin(0), "0000"); Check("二进制 16 位首组补齐", CalcOps.FormatBin(0x1F0), "0001 1111 0000"); Check("有符号 -1", CalcOps.FormatDecSigned(-1), "-1"); Check("无符号 -1", CalcOps.FormatDecUnsigned(-1), "18446744073709551615"); Check("无符号 0", CalcOps.FormatDecUnsigned(0), "0"); Check("负数二进制按补码(-1 = 64 个 1)", CalcOps.FormatBin(-1), "1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111"); Check("负数八进制按补码", CalcOps.FormatOct(-1), "0o1777777777777777777777"); Check("负数二进制 -8", CalcOps.FormatBin(-8), "1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1000"); // ── 位运算 ── Check("12 AND 10 = 8", CalcOps.And(12, 10).ToString(), "8"); Check("12 OR 10 = 14", CalcOps.Or(12, 10).ToString(), "14"); Check("12 XOR 10 = 6", CalcOps.Xor(12, 10).ToString(), "6"); Check("NOT 0 = -1", CalcOps.Not(0).ToString(), "-1"); Check("NOT -1 = 0", CalcOps.Not(-1).ToString(), "0"); Check("1 << 8 = 256", CalcOps.Shl(1, 8).ToString(), "256"); Check("1 << 63 = long.MinValue", CalcOps.Shl(1, 63).ToString(), long.MinValue.ToString()); Check("左移 64 位等价移动 0 位", CalcOps.Shl(1, 64).ToString(), "1"); Check("逻辑右移 -1 >> 60 = 15", CalcOps.ShrLogical(-1, 60).ToString(), "15"); Check("逻辑右移 -8 >> 1 是正数", CalcOps.ShrLogical(-8, 1).ToString(), "9223372036854775804"); Check("移动位数取低 6 位", CalcOps.ShiftCount(65).ToString(), "1"); // ── 位点选 ── CheckTrue("第 3 位为 1", CalcOps.BitAt(8, 3), null); CheckTrue("第 2 位为 0", !CalcOps.BitAt(8, 2), null); Check("置第 0 位", CalcOps.SetBit(0, 0, true).ToString(), "1"); Check("清第 3 位", CalcOps.SetBit(8, 3, false).ToString(), "0"); Check("置第 63 位", CalcOps.SetBit(0, 63, true).ToString(), long.MinValue.ToString()); Check("越界索引不崩", CalcOps.SetBit(7, 99, true).ToString(), "7"); Check("越界取值返回 false", CalcOps.BitAt(7, -1) ? "yes" : "no", "no"); // ── 字节视图 / ASCII ── Check("字节视图大端", CalcOps.ByteView(0x0102030405060708L), "01 02 03 04 05 06 07 08"); Check("字节视图 0", CalcOps.ByteView(0), "00 00 00 00 00 00 00 00"); Check("ASCII Hello(大端,前 3 字节是 0)", CalcOps.AsciiView(0x48656C6C6F), "...Hello"); Check("不可打印字符打点", CalcOps.AsciiView(0x0000000000000001), "........"); Check("popcount 255", CalcOps.PopCountText(255), "8 位为 1"); Check("popcount 0", CalcOps.PopCountText(0), "0 位为 1"); Check("popcount -1", CalcOps.PopCountText(-1), "64 位为 1"); // ── 进制名 ── Check("二进制名", CalcOps.RadixName(2), "二进制"); Check("十 进制名", CalcOps.RadixName(10), "十进制"); } catch (Exception ex) { _fail++; _lines.Add(" [!!] 自测中途异常:" + ex.GetType().Name + " " + ex.Message); } _lines.Add(""); if (_fail == 0) _lines.Add("结果:共 " + (_pass + _fail) + " 项,全部通过 ✓"); else _lines.Add("结果:共 " + (_pass + _fail) + " 项,通过 " + _pass + ",失败 " + _fail + " ✗"); string all = string.Join("\r\n", _lines.ToArray()); Console.WriteLine(all); try { System.IO.File.WriteAllText( System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "selftest-devcalc.txt"), all, new UTF8Encoding(true)); } catch { } return _fail == 0 ? 0 : 1; } } public static class CalcProgram { [STAThread] public static void Main(string[] args) { if (args != null && args.Length > 0 && args[0] == "--selftest") { Environment.Exit(CalcSelfTest.Run(args.Length >= 2 ? args[1] : null)); } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new DevCalcForm()); } } }