我正在使用移动命令,它用于记录值的一个字节到字符串的转换,但是当我添加更多值时,它会显示垃圾值。这是代码
interface
type
tcommand = (
cmd_login,
cmd_logout,
cmd_userinfo,
cmd_removeuser,
cmd_response
);
tprotocol = record
username: string;
receipent_username: string;
arr: tbytes;
case command_id: tcommand of
cmd_userinfo:
(username2: shortstring; ip: shortstring; port: word); // new info
cmd_response:
(status: boolean);
cmd_removeuser:
(username_remove: shortstring);
end;
pprotocol = ^tprotocol;
procedure encode_packet(obj: pprotocol);
procedure decode_packet(arr1: tbytes);
implementation
procedure encode_packet(obj: pprotocol);
begin
setlength(obj.arr, length(obj.username) * 2);
move(obj.username[1], obj.arr[0], length(obj.username) * 2);
setlength(obj.arr, length(obj.receipent_username) * 2);
// SetLength(Destination, SourceSize);
move(obj.receipent_username[1], obj.arr[1],
length(obj.receipent_username) * 2);
// problem starts from here
end;
procedure decode_packet(arr1: tbytes);
begin
setlength(username, length(arr1));
move(arr1[0], username[1], length(arr1));
setlength(s, length(arr1));
move(arr1[1], s[1], length(arr1));
end;
用法:
showmessage(username);
// displays correct value if recepient_username is not encoded
showmessage(s);
procedure TForm1.encodeClick(Sender: TObject); // button click
var
obj2: pprotocol;
begin
new(obj);
new(obj2);
memo1.Lines.Add('encode click');
obj.username := 'ahmd';
obj.receipent_username := 'ali';
encode_packet(obj);
decode_packet(obj.arr);
end;
我想我必须从哪里开始和停止解码字节数组做一些索引,但我不知道怎么做?谁能解释我如何将字符串存储在字节数组中(当我调试时,我看到有数字和一些 nil 值,如果它们与 nil 值混合在一起,如何从索引中获取字符串?)