Forum > Beginners

String to Binary

(1/3) > >>

nugax:
If i have a string say:

String := 'This is a string';

How can i change the to binary(byte) to write to a byte array?

Warfley:
So you mean getting the raw data? Easiest way is probably to simply use move:

--- Code: Pascal  [+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i < x.length; i++) { x[i].style.maxHeight='none'; x[i].style.height = Math.min(x[i].clientHeight+15,306)+'px'; x[i].style.resize = "vertical";}};} ---var  arr: Array of Byte;  str: String;begin  SetLength(arr, Length(str) * SizeOf(str[1]));  Move(Str[1], arr[0], Length(arr));end;
But if you just need to use this data, without relying on the array structure (i.e. reference counted lazy copy) you could cast the address to the first element to a byte pointer and use this as array access. This avoids copying of the data.

marcov:
Check if length() is >0 first? Otherwise dereferencing a NIL array could happen ?

Warfley:
Not really, because the SizeOf is at compile time and the Move parameters are (untyped) const and var so this just takes the pointers to the array elements which no problem as long as the pointers will never be dereferenced (which for length = 0 argument in move they won't).
That said, if range checks are enabled it will fire an exception so while this is a false positive, this could be annyoing so it probably would be better to check

mas steindorff:
we should also add the disclaimer that there are more to strings that what meets the eye. 
Some of the older types have a length byte as the first byte and then there are the strings made of wide (16bit) characters.

Navigation

[0] Message Index

[#] Next page

Go to full version