Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert int to array of bytes in C?

Tags:

c

I need to convert decimal number stored in an int, to a array of bytes (aka stored in a unsigned char array).

Any clues?

like image 394
Emi Avatar asked Aug 10 '10 09:08

Emi


People also ask

How to convert an integer into a specific byte array in c++?

We split the input integer (5000) into each byte by using the >> operator. The second operand represents the lowest bit index for each byte in the array. To obtain the 8 least significant bits for each byte, we & the result with 0xFF . Finally, we print each byte using the print function.

What is byte array in C?

byte array in C An unsigned char can contain a value from 0 to 255, which is the value of a byte. In this example, we are declaring 3 arrays – arr1, arr2, and arr3, arr1 is initialising with decimal elements, arr2 is initialising with octal numbers and arr3 is initialising with hexadecimal numbers.

What is a byte array?

A byte array is simply an area of memory containing a group of contiguous (side by side) bytes, such that it makes sense to talk about them in order: the first byte, the second byte etc..


1 Answers

Or if you know what you are doing:

int n = 12345;
char* a = (char*)&n;
like image 93
leppie Avatar answered Sep 30 '22 09:09

leppie