c# - 如何将两个字节的整数添加到数组中?
问题描述
我需要将一个整数转换为 2 个字节 (0 x...) 我该怎么做?
int port = 7777;
byte[] bufferPost = { 0xBC, 0x5F, ..., 0xbyte1OfIntValue, 0xbyte2OfIntValue };
解决方案
像这样的东西:
byte[] bufferPost = new byte[] {
0x12, 0x23, 0x45};
int port = 7777;
Array.Resize(ref bufferPost, bufferPost.Length + 2);
bufferPost[bufferPost.Length - 2] = (byte)(port & 0xFF);
bufferPost[bufferPost.Length - 1] = (byte)((port >> 8) & 0xFF);
// Let's have a look what's going on
Console.Write(string.Join(" ", bufferPost.Select(item => "0x" + item.ToString("x2"))));
结果:
0x12 0x23 0x45 0x61 0x1e
推荐阅读
- firebase - 设置 firebase 云函数调用
- ios - 我是否在使用基于 HTTP/2 的 Apple 推送通知服务 (APN)?
- python - 如何解决“ AttributeError: 'PathCollection' object has no property 'pred' ”错误?
- python - 使用正则表达式从文本中解析块名称和实例名称
- winapi - WinAPI:您如何获得 UAC 为已签名二进制文件显示的“已验证发布者”?
- python-3.x - Selenium Webdriver (Python):我们可以为文本验证实现页面对象模型吗?
- configuration - 使用 Apache MINA 实现 JGIT TransportConfigCallback
- haproxy - HAProxy ACL 与文件中的用户代理不匹配
- sql - PostgreSQL 条件连接的性能 - 查询优化
- html - 如何使文本区域中的文本开始略低?