Convert 4 bytes in small trailing order to unsigned integer

I have a string of 256 * 4 bytes of data. These 256 * 4 bytes must be converted to 256 unsigned integers. The order in which they find is slightly narrowed, i.e. The first four bytes in the string represent the small final representation of the first integer, the next 4 bytes represent the small final representation of the next integer, etc.

What is the best way to parse this data and combine these bytes into unsigned integers? I know that I need to use bitrate operators, but I don’t know how.

+4
source share
3 answers

Hope this helps you

unsigned int arr[256]; char ch[256*4] = "your string"; for(int i = 0,k=0;i<256*4;i+=4,k++) { arr[k] = ch[i]|ch[i+1]<<8|ch[i+2]<<16|ch[i+3]<<24; } 
+6
source

Alternatively, we can use C / C ++ casting to interpret the char buffer as an unsigned int array. This can help avoid bias and judgment.

 #include <stdio.h> int main() { char buf[256*4] = "abcd"; unsigned int *p_int = ( unsigned int * )buf; unsigned short idx = 0; unsigned int val = 0; for( idx = 0; idx < 256; idx++ ) { val = *p_int++; printf( "idx = %d, val = %d \n", idx, val ); } } 

This will print 256 values, the first of which will be idx = 0, val = 1684234849 (and all other numbers = 0).

As a side note, “ABCD” is converted to 1684234849 because it runs on X86 (Little Endian), in which “ABCD” is 0x64636261 (with 'a' is 0x61, and 'd' is 0x64 - in Little Endian, LSB is in lowest address). So 0x64636261 = 1684234849.

Note that when using C ++ in this case, reinterpret_cast should be used:

 const char *p_buf = "abcd"; const unsigned int *p_int = reinterpret_cast< const unsigned int * >( p_buf ); 
+4
source

If your host system is a little oriented, just read 4 bytes and copy it to int. If your host is a large enditer, do the same and change the bytes in int or change it "on the fly" when copying with bitrate

0
source

Source: https://habr.com/ru/post/1494008/


All Articles