Cast int to char array without impacting heap

421 Views Asked by At

I need to convert an int to a byte array in Micro Framework so it can be streamed to serial. This is happening in a time-sensitive area of the code where a delay caused by the garbage collector could take too long.

Normally I’d cast the int to string and thence to a char array. But that creates a heap object that risks garbage collection.

Is there an efficient way to do this? I can do it in a loop that uses modulo 10 arithmetic but that would be slow. In C I've used sprintf to convert to a pre-allocated array, which would be fine.

2

There are 2 best solutions below

10
pid On

You can use BitConverter for such tasks.

But I'd advise you to take a look at ProtoBuf if you really need to squeeze every ounce of space/performance from the serialized binary. There's hardly a better/faster way to serialize data into binary blobs. Then you will be able to send that over the wire or save to disk, or store it in memory for caching purposes.

1
Christopher Broome On

Not sure if it's available in the Micro Framework, but one of the BitConverter.GetBytes overloads should do the trick.