在 Objective-C 中如何将 int 转换为 byte?
我有一个 int 值需要转换为字节数组。 你如何在 Objective-C 中做到这一点?有没有方法可以做到这一点?
谢谢你,
I have an int value which needs to be converted into a byte array.
How do you go about doing this in Objective-C? Are there methods to do this?
Thank you,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
通过什么方式转换的?您想要小端、大端还是本机字节顺序?如果您希望它采用本机字节顺序,那么您需要做的就是:
也就是说,操作整数字节的最佳方法是进行按位运算。例如,要获取最低位字节,可以使用 val&0xFF,要获取下一个字节,可以使用
(val>>8)&0xFF
,然后使用(val>> 16)&0xFF
,然后(val>>24)&0xFF
,等等。当然,这取决于你的数据类型的大小。如果你做这些事情,你真的应该包括
<
inttypes.h
>
;,并使用uint8_t
、uint16_t
、uint32_t
或uint64_t
,具体取决于您想要多大的整数;否则,您无法可靠地使用更大数量的字节。Converted in what way? Do you want it in little endian, big endian, or native byte order? If you want it in native byte order, then all you need to do is:
That said, the best way to manipulate the bytes of an integer is to do bitwise operations. For example, to get the lowest order byte, you can use val&0xFF, to get the next you use
(val>>8)&0xFF
, then(val>>16)&0xFF
, then(val>>24)&0xFF
, etc.Of course, it depends on the size of your data type. If you do those kinds of things, you really should include
<
inttypes.h
>
;, and useuint8_t
,uint16_t
,uint32_t
, oruint64_t
, depending on how large an integer you want; otherwise, you cannot reliably play around with larger numbers of bytes.我怀疑您想要做的是将这个字节数组传递给 NSMutableData 对象。您只需传递地址 &val
示例:
此链接更完整并处理字节顺序:
Append NSInteger to NSMutableData
I suspect that what you want to do is to pass this byte array somewhere possibly to a NSMutableData object. You just pass the address &val
Example:
This link is more complete and deals with endianness:
Append NSInteger to NSMutableData