在 GNU 汇编器中声明固定长度的填充字符串
我试图在汇编程序中以固定大小的结构定义一些数据。我想声明固定字节数的字符串数据,并用字符串初始化。在 C 语言中,它是:
char my_string[32] = "hello";
32 字节,并在末尾填充任意多个零。
汇编程序中的等价物是什么?我知道我可以手动计算字符串的长度并声明必要的零字节数以填充到 32,例如:
my_string:
.asciz "hello"
.zero 26
但是如果字符串是动态定义的(例如从外部定义或包含),我该怎么做?
I'm trying to define some data in a fixed-size structure in assembler. I'd like to declare string data of a fixed number of bytes, initialised with a string. In C it would be:
char my_string[32] = "hello";
Which is 32 bytes, and padded with however many zeros needed at the end.
What would be the equivalent in assembler? I know I can manually count the length of my string and declare the necessary number of zero bytes to pad to 32, e.g.:
my_string:
.asciz "hello"
.zero 26
But how can I do it if the string is being defined dynamically, such as from an external define or include?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我想我会为此使用带有本地标签的宏。例如:
...像这样使用:(
如果字符串恰好是
max
个字符长,则这具有类似 C 的行为,不添加终止 0。要确保字符串终止,只需更改 <代码>.ascii 到.asciz
。)I think I'd use a macro with local labels for this. For example:
...used like this:
(This has C-like behaviour of not adding the terminating 0 if the string is exactly
max
characters long. To ensure the string is terminated, just change the.ascii
to.asciz
.)您所描述的仍然是一个静态字符串,尽管大小未知。您可以通过从当前数据指针($)中减去字符串的地址来获得字符串的大小。从最大大小中减去字符串的大小,您就知道要添加多少个零:
可以简化为:
What you are describing is still a static string, albeit of unknown size. You can get the size of the string my subtracting the address of the string from current data pointer ($). Subtract the size of the string from the maximum size and you know how many zeroes to add:
which can be simplified to:
我更喜欢 Jens 的回答 使用例如
.zero (32+my_string-$)
,但是我收到错误消息错误:.space指定非绝对值
。这似乎是一个可行的替代方案:
我不知道它是否保证将整个 32 个字节设置为特定值(即尾部字节用零填充),但使用
.asciz
确实确保了字符串是零终止的。I would have preferred Jens' answer of using e.g.
.zero (32+my_string-$)
, however I got the error messageError: .space specifies non-absolute value
.This seems to be a viable alternative:
I don't know if it guarantees that the whole 32 bytes are set to particular values (i.e. trailing bytes filled with zeros), but using
.asciz
does ensure the string is zero-terminated.