Re: {Spam?} writing binary files
Pontus Rodling <[email protected]> Wed, 3 May 2017 17:17:26 +1200
| Newsgroups | gmane.comp.lang.pike.user |
|---|---|
| Message-ID | <[email protected]> |
Hi,
There's an even easier way if you have an array of ints.
Casting the array to a string will turn each element of the array into a
character:
> array(int) arr = ({ 4, 5, 9, 12, 255, 0, 8 });
> (string)arr;
(1) Result: "\4\5\t\f\377\0\b"
So just f->write((string)arr) would work.
The same thing also works in reverse:
> (array)"\4\5\t\f\377\0\b";
(3) Result: ({ /* 7 elements */
4,
5,
9,
12,
255,
0,
8
})
Most of the time I typically just operate on indexes in the string when
dealing with binary formats, like:
> string s = "abc";
> s[1] = 'd';
> s;
(7) Result: "adc"
Range operators are also incredibly helpful, and are applicable to both
strings and arrays (great for parsing binary formats):
> string s = "potato";
> s[2..];
(8) Result: "tato"
> s[2..3];
(9) Result: "ta"
> s[2..<1];
(10) Result: "tat"
> s[1..<2];
An important thing to note as well is that a character is not limited to
0-255, larger values are allowed to support unicode strings, or
'widestrings'.
Only thing to remember is that a widestring would need to be encoded
when writing to a file, for example using UTF-8.
> string a = "\u1234";
> a[0];
(17) Result: 4660
> string_to_utf8(a);
(18) Result: "\341\210\264"
Happy file writing :)
Best regards,
Pontus
On 05/02/2017 06:04 AM, larcky wrote:
> Hi thanks for reply!
> That example was perfect but also as you suggested...
>
> int main()
> {
> Stdio.File f = Stdio.File("foo.bin", "wct");
> array(int) arr = ({ 4, 5, 9, 12, 255, 0, 8 });
> *f->write( sprintf("%{%c%}", arr) );*
> f->close();
> return 0;
> }
>
> Pike=awesome
>
>
>
> --
> View this message in context: http://pike.1058338.n5.nabble.com/writing-binary-files-tp5713245p5713247.html
> Sent from the Pike - User mailing list archive at Nabble.com.
>