home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #27 / NN_1992_27.iso / spool / comp / lang / cplus / 16510 < prev    next >
Encoding:
Internet Message Format  |  1992-11-18  |  2.1 KB

  1. Path: sparky!uunet!olivea!spool.mu.edu!yale.edu!ira.uka.de!slsvaat!josef!kanze
  2. From: kanze@us-es.sel.de (James Kanze)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: packing/unpacking unsigned in char ?
  5. Message-ID: <KANZE.92Nov18160657@slsvdnt.us-es.sel.de>
  6. Date: 19 Nov 92 00:06:57 GMT
  7. References: <1992Nov15.225151.7502@imada.ou.dk>
  8. Sender: news@us-es.sel.de
  9. Organization: SEL
  10. Lines: 55
  11. In-Reply-To: adelt@imada.ou.dk's message of Sun, 15 Nov 1992 22:51:51 GMT
  12.  
  13. In article <1992Nov15.225151.7502@imada.ou.dk> adelt@imada.ou.dk (Adel
  14. Shavandi) writes:
  15.  
  16. |> I need some suggestions for an effective and correct way to
  17. |> pack/unpack unsigneds in [0,127] in chars and communicate
  18. |> them to another process.  
  19.  
  20. |> What i do myself is as the following code:
  21.  
  22.  
  23. |> // child process:
  24. |>     // ...
  25. |>     unsigned num1;
  26. |>     // ...
  27. |>     // num1 is in [0,127] now
  28. |>     printf("%c",num1); // later is rediercted to parent by pipe mech.
  29. |>     // ...
  30.  
  31.  
  32. |> // parent process:
  33. |>     // ...
  34. |>     unsigned num2;
  35. |>     char ch;
  36. |>     int n=read (fd,&ch,1);
  37. |>     if (n>0)
  38. |>         num2=(unsigned) ch;
  39. |>     // ...
  40.  
  41.  
  42. |> Now i know this may be wrong since sometimes i receive some wrong
  43. |> numbers. Any ideas/suggestions ?
  44.  
  45. |> But what is interesting is that the wrong numbers are very similiar
  46. |> each time. Am i confronting with pitfalls ?! 
  47.  
  48. You don't say what OS you're using.
  49.  
  50. On most non-Unix systems (MS-DOS, for example), there is a distinction
  51. between binary files and text files.  In such cases, stdout (which
  52. printf uses) is normally opened as a *text* file.  Independantly of
  53. this, I'm not sure what the implications would be of using printf on a
  54. binary file.
  55.  
  56. As an example of the difference, in a text file, MS-DOS will convert
  57. the character '\n' (0x0a) to a two character sequence 0x0d,0x0a.
  58.  
  59. So the correct solution is to open a file (don't use stdout) for
  60. binary output (fopen( <filename> , "wb" )), and output to it, with
  61. either fwrite or putc.  (On some systems, it's possible to change the
  62. mode of stdout, but this is non-portable.)
  63. --
  64. James Kanze            GABI Software, Sarl.
  65. email: kanze@us-es.sel.de    8 rue du Faisan
  66.                 67000 Strasbourg
  67.                 France
  68.