Reading bytes and converting to int

David d at dav1d.de
Sat Aug 25 13:30:09 PDT 2012


Am 25.08.2012 22:18, schrieb joao:
> On Saturday, 25 August 2012 at 20:03:38 UTC, Jonathan M Davis wrote:
>> On Saturday, August 25, 2012 21:50:58 joao wrote:
>>> Thanks everyone, I solved the problem.
>>> I didn't understand these bitmanip methods so I searched and
>>> found a function to do what I wanted:
>>>
>>> string b = "\x24\x10\x00\x00";
>>> uint i = byteToInt(b);
>>> uint byteToInt(string b) {
>>>      return b[0] | b[1] << 8 | b[2] << 16 | b[3] << 24;
>>> }
>>>
>>> => 4132
>>
>> What's hard to understand about them? I thought that they were very
>> straightforward.
>>
>> This will do essentially the same thing:
>>
>> import std.bitmanip;
>> import std.system;
>>
>> void main()
>> {
>>     ubyte[] b = [0x24, 0x10, 0x00, 0x00];
>>     auto i = peek!(uint, Endian.littleEndian)(b);
>>     assert(i == 4132);
>> }
>>
>> Use peek if you don't want to consume the buffer and read if you do.
>>
>> - Jonathan M Davis
>
> It's not hard, sorry, it's because I'm a begginner.
> So, all I wanted to do was to open a file and read the first 4 bytes and
> then return the int value. The last part I managed to do.
> But the first I'm trying.
>
> In Python it is something like this:
> f = open('filename')
> s = f.read(4)
> ...
> In D I don't know yet. I'm trying to do:
> File f = File('filename')
> Then I want to read just 4 bytes. I still don't know what method is :P

File f = File("filename");
auto buf = f.rawRead(new ubyte[4]);


More information about the Digitalmars-d-learn mailing list