M
Modular•12mo ago
zverianskii

string chars to uint8

Any examples on how to access string characters and convert them to something similar to python bytes? In general any examples of types conversion would be helpful
6 Replies
zverianskii
zverianskii•12mo ago
Anyone?😭
TeamPuzel
TeamPuzel•12mo ago
Hi, the built in String type is not documented very well, but you can make an array of UInt8 which is enough to represent an ascii string You could use the built in DynamicVector or a more complete array implementation made by the community for this If you see for example the Rust implementation of a String it's literally just
pub struct String {
vec: Vec<u8>,
}
pub struct String {
vec: Vec<u8>,
}
with a bit of methods on it If you don't need utf8 it's not too difficult to make one I also ran into this issue so I decided to write my own String, however Mojo types like UInt8 are just aliases for SIMD types which is also painful There is currently a bug in the compiler that makes it impossible to implement your own UInt8 and by extension String without some hacks Hopefully in the near future that is fixed, or even better, maybe the Mojo String will get some improvements
zverianskii
zverianskii•12mo ago
Thanks
Jack Clayton
Jack Clayton•12mo ago
Hi @zverianskii is this what you're looking for:
from builtin.string import ord
fn main():
let s = String("Mojo!")
print(ord(s[0]))
from builtin.string import ord
fn main():
let s = String("Mojo!")
print(ord(s[0]))
Or you can do like this:
from builtin.string import ord


fn main():
let s = String("Mojo!")
let b = s._buffer
for i in range(len(b)):
print(b[i])
_ = s
from builtin.string import ord


fn main():
let s = String("Mojo!")
let b = s._buffer
for i in range(len(b)):
print(b[i])
_ = s
77 111 106 111 33 String internal representation is subject to change though for small string optimizations, so using s._buffer might break your code in the future
zverianskii
zverianskii•12mo ago
Thanks @Jack Clayton could you please provide some info why _ = s changes output?
mad alex 1997
mad alex 1997•12mo ago
Prevents compiler from destroying s prematurely.
Want results from more Discord servers?
Add your server