Convert a string character to Byte?

BlitzMax Forums/BlitzMax Beginners Area/Convert a string character to Byte?

Grey Alien(Posted 2006) [#1]
Hi, how can I convert a string character (i.e obtained by using Mid(mystring$, n, 1) into a Byte ready for writing to a stream. I know I can write strings to streams but I want to manipulate the byte value before saving.

This just generates junk, presumeably because it strings are made from unicode characters (16 bits yes?):

Local b:Byte = Byte(Mid(name$,i,1))
Thanks!


Ghost Dancer(Posted 2006) [#2]
Asc() should do the trick - this will return the value of the string. e.g.

Local b:Byte = Asc(Mid(name$,i,1))


Not sure exactly what you are doing, but when you read your data back out, you may need to convert it back with Chr()


Yan(Posted 2006) [#3]
myStream.WriteByte(name$[i])



Grey Alien(Posted 2006) [#4]
thanks guys. I should have remembered ASC (used to use it years ago), I was looking through the docs and thinking, what is the opposite of chr()!

Ian: I'm surprised that works, but I trust you, so great! I thought that sort of thing only worked with null terminated strings that are fixed length because dynamic strings of any length are not necessarily stored contiguously in the memory and the characters are not single bytes any more. But maybe I'm thinking of Delphi ...


N(Posted 2006) [#5]
I thought that sort of thing only worked with null terminated strings that are fixed length because dynamic strings of any length are not necessarily stored contiguously in the memory and the characters are not single bytes any more. But maybe I'm thinking of Delphi ...


You probably are. If you look at the BBString structure it's obvious that the data is a contiguous block of memory.


Grey Alien(Posted 2006) [#6]
OK cool, that's why it works then.


Tibit(Posted 2006) [#7]
Local b:Byte = Asc(Mid(name$,i,1))

If mid does: Mid( StringtoSearch$, WhereToStart%, LengthToRead% )

So you could write the above like this:
local b:Byte = Name[i] 



Yan(Posted 2006) [#8]
Ian: I'm surprised that works, but I trust you, so great! I thought that sort of thing only worked with null terminated strings that are fixed length because dynamic strings of any length are not necessarily stored contiguously in the memory and the characters are not single bytes any more. But maybe I'm thinking of Delphi ...
I don't pretend to know how it works, it's compiler voodoo. :o)

It should be noted that you can't write to strings in this way and you should probably be using shorts if you intend to be Unicode compatible.


Grey Alien(Posted 2006) [#9]
Wave: Thanks, so easy lol, I ust assumed that wouldn't work as strings may have been stored differently.

Ian: thanks, I was using bytes, so I could use WriteByte to a stream.