Skip to content

Recommended way of interpreting bytes as e.g. Int32? #2297

Locked Answered by mikowals
fnands asked this question in Q&A
Discussion options

You must be logged in to vote

I think bitcasting the pointer is the normal way to do this. This is unlikely to remain the "recommended" way for long as special handling for bytes is likely to be added. See this or this

A code example:

from testing import assert_true
from collections import List

fn bytes_to_uint32(owned list: List[Int8]) raises -> List[UInt32]:
  assert_true(len(list) % 4 == 0, "List[Int8] length must be a multiple of 4 to convert to List[Int32]")
  var result_length = len(list) // 4
  
  # get the data pointer with ownership.
  # This avoids copying and makes sure only one List owns a pointer to the underlying address.
  var ptr_to_int8 = list.steal_data() 
  var ptr_to_uint32 = ptr_to_int8.bitcast[U…

Replies: 5 comments 1 reply

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Answer selected by fnands
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
1 reply
@fnands
Comment options

Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants