Read a number from a stream

BlitzMax Forums/BlitzMax Programming/Read a number from a stream

Seb67(Posted 2009) [#1]
Hi everyone, I'm new on this forum.

I'm trying to read an Int value from a stream, but ReadInt reads 4 characters, and I'd like to read a value that has a dynamic number of characters.

I made a sequence who determines how much characters I have between "@x" and "*", but how to read them ?

Can I read a String$ and convert it to an Int ? How can I do that ?

Thank you very much.


_JIM(Posted 2009) [#2]
Are you trying to read an Int that has been compressed to 1 up to 4 bytes? If so, then you can read each character as a byte then fill the Int:

Local ptr_to_value:Byte Ptr = VarPtr(your_read_value)
Local ptr_to_int:Byte Ptr = VarPtr(your_int)

ptr_to_int[0] = ptr_to_value[0]

'if you have more characters, write more
ptr_to_int[1] = ptr_to_value[1]

'and so on
'I think the values are stored in reverse order though but I'm not sure



If you're trying to read a String of variable length then you can either read it byte by byte (which may be a bad idea) or read it in chunks then trim your value.

If you are trying to read a number that is either a byte, short, (3-byte decimal), int, (5-byte decimal) etc. then I don't know how to help you further as this looks to me like a design error somewhere.

Edit:

As to converting a string to an int:
If your string looks like "16490" then a simple cast would do:
myInt:Int = Int(my_string)


If your string actually contains the Int in binary form, then this might be a bad idea again because if the string contains the null character (0 as in 0x00000000) then it treats it as the end of the string. Either way, you can still recover the int:

Local ptr_to_string:Byte Ptr = Varptr(my_string)
Local my_int:Int
Local ptr_to_int:Byte Ptr = Varptr(my_int)

ptr_to_int[0] = ptr_to_string[0]
ptr_to_int[1] = ptr_to_string[1]
ptr_to_int[2] = ptr_to_string[2]
ptr_to_int[3] = ptr_to_string[3]



Seb67(Posted 2009) [#3]
Thanks, I didn't think that Int(String$) would work.


xlsior(Posted 2009) [#4]
Thanks, I didn't think that Int(String$) would work.


It does, but do make sure to sanity-check your string first, or it will blow up when you pass characters that can't be converted to an int.


Czar Flavius(Posted 2009) [#5]
It won't blow up, but it might give an unusual answer. If there is a number followed by a non-number character, it returns that first number and ignores the rest. If there is no number first, it will return 0.