Is were anything like ToBytes in Type String?

BlitzMax Forums/BlitzMax Programming/Is were anything like ToBytes in Type String?

Fabian.(Posted 2005) [#1]
In Type String there's a function FromBytes:String( bytes:Byte Ptr,length ) which creates a string from bytes.
But there's no method like ToBytes( bytes:Byte Ptr, length ) which copys a string to bytes in memory.
Is there another way?


deps(Posted 2005) [#2]
ToCString()


GW(Posted 2005) [#3]
whats wrong with StringVar[index] ?


Koriolis(Posted 2005) [#4]
It doesn't help you if you have to pass the string to a function that expects a byte pointer.


Fabian.(Posted 2005) [#5]
When I'm using ToCString(), can I be sure that every char is copied to returned memory, or will it stop after the first null char?
(I want to create a byte or short array, so I don't really know whether I really should use ToCString())

Thanks for help!


taxlerendiosk(Posted 2005) [#6]
CreateRamStream and then WriteString to that?


Azathoth(Posted 2005) [#7]
C strings always end with a null char, even other languages do this too.


ziggy(Posted 2005) [#8]
I don't know what happens when you make .toCString

there are two possible ways to implement toCString:

1.- Making a copy of the string contents with a null char added at the end and returning a byte pointer to this ram bank. In this case, you should use banks instead of strings.

2.- returning a byte pointer to the bank where the BlitzMax string is already allocated. In this case you could pass also the lenght of the string, and you would have your problem solved.


Azathoth(Posted 2005) [#9]
I remember somewhere you have to free the memory returned by .ToCString() as its not handled by the gc.


Fabian.(Posted 2005) [#10]
C strings always end with a null char, even other languages do this too.
And exactly this is my problem - I don't want to have a C string, I want to have a byte or short array. Something like this would help me:
Strict

Function StringToShortArray:Short [] ( S$ )
  Local Shorts:Short [ Len S ]
  MemCopy Shorts , 4 + Byte Ptr Object S , 2 * Len Shorts
  Return Shorts
EndFunction

Function StringToShorts ( S$ , Shorts:Short Ptr )
  MemCopy Shorts , 4 + Byte Ptr Object S , 2 * Len S
EndFunction

Function StringToByteArray:Byte [] ( S$ )
  Local Bytes:Byte [ Len S ]
  For Local I = 0 Until Len S
    Bytes [ I ] = S [ I ]
  Next
  Return Bytes
EndFunction

Function StringToBytes ( S$ , Bytes:Byte Ptr )
  For Local I = 0 Until Len S
    Bytes [ I ] = S [ I ]
  Next
EndFunction
I could write a module for this.
But I don't really want to write a module for only four functions.