简体   繁体   中英

Convert integer to byte array

I am having a hard time trying to perform what should be a simple conversion from an integer to a byte array.

I feel this must be simple, even trivial, but cannot get it (so if anyone know the right "name" for this operation, please tell me). Also, I couldn't find a better question title, but I feel it's a bit vague (feel free to edit).

What I want:

byte[] result = MagicConverter.Convert(336);
// now result should be {0, 0, 1, 80}

The result of converting 336 should be 1, 80 because that is the decomposition in base 256, that is, 1*256 + 80 = 336.

My codebase contain a lot of bitshifting stuff to perform similar tasks, but I think I'm not quite inderstanding this bitshifting thing yet.

BitConverter.GetBytes(366); 

应该做到的。

您正在寻找的是BitConverter.GetBytes()

byte[] result = BitConverter.GetBytes(366);

您可以使用BitConverter.GetBytes()函数执行此操作。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM