是否有任何方法可以将2个循环绑定在C#中的循环中。
- 它从MCU读取消息并将它们存储在8个字节[0]〜[7]的代码中,
- 特别是在上半年存储前4个元素,索引[0]〜[3]和接下来的四个元素在接下来的半部分中,索引[4]〜[7]
- 是否有任何更轻松的方法?
halfbytelength = 4;
bytelength =8;
case 0:
for (index = 0; index <halfbytelength; index += 1)
{
Array1[index] = msg[index];
}
for (index = halfbytelength; index < bytelength; index += 1)
{
Array2[index - halfbytelength] = msg[index];
}
MainArray[0] = ASCIIEncoding.ASCII.GetString(Array1);
MainArray[1] = ASCIIEncoding.ASCII.GetString(Array2);
- The code where it reads Messages from MCU and stores them in an array of 8 bytes[0]~[7],
- specifically storing the first 4 elements in the first half, indexes [0] ~[3], and the next four elements in the next half, indexes [4] ~[7]
- Is there any easier way to do it?
halfbytelength = 4;
bytelength =8;
case 0:
for (index = 0; index <halfbytelength; index += 1)
{
Array1[index] = msg[index];
}
for (index = halfbytelength; index < bytelength; index += 1)
{
Array2[index - halfbytelength] = msg[index];
}
MainArray[0] = ASCIIEncoding.ASCII.GetString(Array1);
MainArray[1] = ASCIIEncoding.ASCII.GetString(Array2);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不需要编写循环以自己复制字节。例如,您可以使用跨度切片阵列。
我想说的是,阅读要容易得多。或<添加扩展方法将跨度转换为直接将跨度转换为字符串。
或者您可以使用阵列。副本
,但我发现阅读不太容易。
关于性能,我不会期望有很大的差异。我希望将数组转换为字符串比复制几个字节要多。但是,如果避免分配的任何方法在紧密的循环中运行,则可能会具有一定的优势。
There should be no need to write the loop to copy bytes yourself. You could for example use spans to slice the array.
I would say that it is significantly easier to read. Or add an extension method to convert a span to string directly.
Or you could use Array.Copy
But I find that less easy to read.
With regards to performance I would not expect a huge difference. I would expect converting the array to a string to take more time than copying a few bytes. But any method that avoid allocations might have some advantage if it is run in a tight loop.
假设
bytelength
保持甚至,您可以用以下来用1 替换2个循环:注: @JeremyLakeman commented
Assuming that
bytelength
stays even, you can do the following to replace your 2 loops with 1:Note: as @JeremyLakeman commented below, using
Array.Copy
might be faster.Your code will also be shorter (1 line per array, with no loops).
(assuming that
msg
,Array1
,Array2
are of array type - which you didn't specify in your question).