在 NXC 中将有符号 int 分成字节
NXC 中有没有办法将有符号整数转换为字节数组?由于语言限制,我也无法使用显式类型转换或指针。
我已经尝试过:
for(unsigned long i = 1; i <= 2; i++)
{
MM_mem[id.idx] = ((val & (0xFF << ((2 - i) * 8)))) >> ((2 - i) * 8));
id.idx++;
}
但失败了。
编辑:这有效......只是没有下载。我浪费了大约一个小时试图弄清楚。 >>_>>
编辑:在 NXC 中,>>
是算术移位。 int
是有符号的 16 位整数类型。 byte
与 unsigned char
相同。
NXC 是“不是确切的 C”,是 C 的亲戚,但与 C 明显不同。
Is there any way to convert a signed integer into an array of bytes in NXC? I can't use explicit type casting or pointers either, due to language limitations.
I've tried:
for(unsigned long i = 1; i <= 2; i++)
{
MM_mem[id.idx] = ((val & (0xFF << ((2 - i) * 8)))) >> ((2 - i) * 8));
id.idx++;
}
But it fails.
EDIT: This works... It just wasn't downloading. I've wasted about an hour trying to figure it out. >_>
EDIT: In NXC, >>
is a arithmetic shift. int
is a signed 16-bit integer type. A byte
is the same thing as unsigned char
.
NXC is 'Not eXactly C', a relative of C, but distinctly different from C.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
怎么样
How about
在 NXC 中使用底层 VM 中可用的操作码执行此操作的最佳方法是使用 FlattenVar 将任何类型转换为字符串(也称为在末尾添加 null 的字节数组)。它会产生单个 VM 操作码操作,其中使用移位、逻辑 AND 和数组操作的上述任何选项都将需要数十行汇编语言。
获得有关 LEGO MINDSTORMS 和 NXT 以及 Not eXactly C 帮助的最佳方式是通过思维板论坛,网址为 http://forums。 Mindboards.net/
The best way to do this in NXC with the opcodes available in the underlying VM is to use FlattenVar to convert any type into a string (aka byte array with a null added at the end). It results in a single VM opcode operation where any of the above options which use shifts and logical ANDs and array operations will require dozens of lines of assembly language.
The best way to get help with LEGO MINDSTORMS and the NXT and Not eXactly C is via the mindboards forums at http://forums.mindboards.net/
问题最初标记为c;这个答案可能不适用于Not eXactly C。
这有什么问题:
您可以将其视为展开的循环。可以省略零移位;优化器肯定会这样做。即使未定义右移负值的结果,也没有问题,因为此代码仅访问定义了行为的位。
此代码以小端顺序给出字节 - 最低有效字节位于
bytes[0]
中。显然,大端顺序是通过以下方式实现的:Question originally tagged c; this answer may not be applicable to Not eXactly C.
What is the problem with this:
You can regard it as an unrolled loop. The shift by zero could be omitted; the optimizer would certainly do so. Even though the result of right-shifting a negative value is not defined, there is no problem because this code only accesses the bits where the behaviour is defined.
This code gives the bytes in a little-endian order - the least-significant byte is in
bytes[0]
. Clearly, big-endian order is achieved by: