Tyler asked:
> I assume that could be done to get the equiv of the 
> microsoft lobyte, loword, hiword, hibyte and etc?
> If that's to combine them, how would you get them apart?

I should have stressed that the conversion from integer to 
chars is implementation-independent. C guarantees a char to 
be a single byte (not necessarily of 8 bits!) and that 
integers are represented in such a way that bitwise 
operations on them make sense. (Otherwise there'd be little 
point in having bitwise operators.)

I don't know what Microsoft's own types are but they're 
probably #define'd in a header file somewhere in terms of 
C's basic types. The Gnu C library does this for its own 
types like uint32_t (guaranteed to be 32 bits no matter what 
machine is used).

To go the other way (char[] to integer) can be done using 
shift and add operations:

#include <stdio.h>
#include <limits.h>

int main(void)
{
  unsigned long long i = 1234567890;
  unsigned long long j;
  unsigned char c[4];

  printf("Your integers are %i bits\n", CHAR_BIT * 
sizeof(i));

  /* Integer to char[]: */

  c[0] = i & 0xff;  /* least significant byte */
  c[1] = (i & 0xff00) >> 8;
  c[2] = (i & 0xff0000) >> 16;
  c[3] = (i & 0xff000000) >> 24;

  printf("0x%08x == ", i);
  printf("0x%02x%02x%02x%02x", c[3], c[2], c[1], c[0]);

  /* char[] to integer: */

  j = c[0] + (c[1] << 8) + (c[2] << 16) + (c[3] << 24);
  printf(" == 0x%08x\n", j);

  return 0;
}

You need to ensure that your integer type is big enough to 
hold the result without overflowing!

David

Reply via email to