code_junkie

How to convert struct to char array in C

Nov 13th, 2011
183
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.50 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. struct x
  4. {
  5. int x;
  6. } __attribute__((packed));
  7.  
  8.  
  9. int main()
  10. {
  11. struct x a;
  12. a.x=127;
  13. char *b = (char *)&a;
  14. int i;
  15. for (i=0; i<4; i++)
  16. printf("%02x ", b[i]);
  17. printf("n");
  18. for (i=0; i<4; i++)
  19. printf("%d ", b[i]);
  20. printf("n");
  21. return 0;
  22. }
  23.  
  24. printf("%02hhx", b[i]);
  25.  
  26. for (i=0; i<4; i++)
  27. printf("%02x ", (unsigned char)b[i]);
  28.  
  29. unsigned char *b = (unsigned char *)&a;
  30.  
  31. for (i=0; i<4; i++) {
  32. //...
  33. }
  34.  
  35. for (i=0; i<sizeof(x); i++) {
  36. //...
  37. }
Add Comment
Please, Sign In to add comment