c# - 如何在 C# 中将数字转换为无符号短(始终为 16 位,大端字节序)
问题描述
我正在寻找相当于 PHP pack() 的 C# 方法
我在 Google 上找到了很多关于此的文章,但是当我尝试了一些代码时,结果总是与使用我的 PHP 代码不同。我不知道。
这是我想在 C# 代码中传输的 PHP 代码。
$binaryMagic = pack("n", 0xbabe);
解决方案
这段代码应该给你同样的结果:
string hex = "babe";
byte[] bytes = new byte[hex.Length / 2];
for (int i = 0; i < hex.Length; i += 2) {
bytes[i/2] = Convert.ToByte(hex.Substring(i, 2), 16);
}
string converted = System.Text.Encoding.UTF8.GetString(bytes, 0, bytes.Length);
Console.WriteLine(converted);
推荐阅读
- python - 在“n”个减少后找到给定列表中唯一数字的最小(最少)个数
- security - 如何保护服务器上的数据加密密钥?
- javascript - File Object Not Defined NuxtJS AsyncData()
- python - 在会话结束之前从 tensorflow 张量中释放内存
- javascript - 从javascript中的模数字符串获取RSA密钥大小
- python - 如何在 Python 中重构 `with` 语句以使用 pandas 数据框?
- typescript - 无法在打字稿中键入动态键
- python-3.x - 在 RHEL7 上使用 pip 安装 boto3 时出错 - 隧道连接失败:502 Bad Gateway
- python - 在python中继承多个类而不进行多次初始化
- javascript - 使用JS通过数学运算修改样式元素