首页 > 解决方案 > 如何在 C# 中将数字转换为无符号短(始终为 16 位,大端字节序)

问题描述

我正在寻找相当于 PHP pack() 的 C# 方法

我在 Google 上找到了很多关于此的文章,但是当我尝试了一些代码时,结果总是与使用我的 PHP 代码不同。我不知道。

这是我想在 C# 代码中传输的 PHP 代码。

$binaryMagic = pack("n", 0xbabe);

标签: c#php

解决方案


这段代码应该给你同样的结果:

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);

推荐阅读