C# 将 int 转换为 2 个字节的数组

标签 c# arrays int

如果我的问题不够清楚,我提前道歉,我没有太多的 c# 经验,我遇到了一个奇怪的问题。 我试图将一个 int 转换为两个字节的数组(例如:取 2210 并得到:0x08、0xA2),但我得到的只是:0x00、0xA2,我不明白为什么。非常感谢任何建议。 (我试过阅读有关此事的其他问题,但找不到有用的答案)

我的代码:

        profile_number = GetProfileName(); // it gets the int 
        profile_num[0] = (byte) ((profile_number & 0xFF00));
        profile_num[1] = (byte) ((profile_number & 0x00FF));
        profile_checksum = CalcProfileChecksum();

//注意:我指的是 2 字节数组,所以关于 4 字节数组的问题的答案对我没有帮助。

最佳答案

您需要移动第一个字节:

 //profile_num[0] = (byte) ((profile_number & 0xFF00));
 profile_num[0] = (byte) ((profile_number & 0xFF00) >> 8);
 profile_num[1] = (byte) ((profile_number & 0x00FF));

关于C# 将 int 转换为 2 个字节的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31716735/

相关文章:

c# - 将对象添加到 Entity Framework 上下文大约需要 1.5 秒

c# 文件移动(文件已被另一个进程使用)

c - 如何将 scanf 与二维数组一起使用以及如何将分配的数组作为参数传递给函数?

C# - 引用 "this int"参数

c# - System.Timers.Timer 是否在独立线程中运行?

c# - .NET 4.5 的奇怪文本框问题 - 不允许 '.'

php - PHP 中的数组是作为值复制还是作为对新变量的引用,以及何时传递给函数?

php 将 stdClass 对象转换为数组

c++ - 从 int 到 char* 没有字符串,和 fstream 不方便

SQL Server int 长度属性