使用指针将十进制转换为二进制 [英] Converting Decimal to Binary using pointers
问题描述
我正在尝试访问程序的内存,以便将十进制输入转换为二进制输出。我目前正在尝试使用@input访问我的整数的起始地址,然后每次将地址递增1并将此地址的值写入控制台。
例如:
- 输入:2
- 输出:00000000000000000000000000000010
有人可以给我一些技巧(或指针吗?哈哈),该怎么做?谢谢。
我不是100%肯定我了解您的要求。
您可以使用类似的函数将值转换为二进制表示形式,该函数取自Indy单元 IdGlobalProtocols
。
function IntToBin(Value:LongWord):字符串;
var
i:整数;
begin
SetLength(Result,32); i的
:= 1至32如果((Value shl(i-1))shr 31)= 0则开始
然后开始
结果[i]:='0'
结束,否则开始
Result [i]:='1';
结尾;
结尾;
结尾;
另一方面,也许您只是在问如何将地址加1。好吧,获取地址并添加一个。您可以通过两种方式执行此操作。如果要将地址作为数字处理,请将其转换为指针大小的整数:
var
地址:UIntPtr;
....
地址:= UIntPtr(@someVar);
现在您可以执行算术运算了。例如:
inc(Address);
地址:=地址+ 8;
等等。
如果实际上希望执行指针算术,然后取消对指针的引用,因此使用指针类型更容易。因此,如果您希望选择字节,则可以这样操作:
var
BytePtr:PByte ;
....
BytePtr:= PByte(@someVar);
现在,您可以使用
<$读取字节p $ p>
b:= BytePtr ^;
下一个是:
inc(BytePtr);
b:= BytePtr ^;
最后,如果要提取组成整数的字节,则有 LongRec
类型。写入 LongRec(someIntVar).Bytes [i]
读取组成整数的4个字节之一。存在类似的记录 WordRec
和 Int64Rec
。这些类型在 SysUtils
中定义。
I'm trying to access the memory of my program in order to convert a decimal input to a binary output. What I'm currently attempting to do is access the starting address of my integer with @input, then increment the address by 1 every time and writing the value of this address to the console.
For example:
- Input: 2
- Output: 00000000000000000000000000000010
Could anyone give me some tips (or pointers? ha ha) on how to do this? Thanks.
I'm not 100% sure I understand what you are asking.
You can convert a value to its binary representation using a function like this, taken from the Indy unit IdGlobalProtocols
.
function IntToBin(Value: LongWord): string;
var
i: Integer;
begin
SetLength(Result, 32);
for i := 1 to 32 do begin
if ((Value shl (i-1)) shr 31) = 0 then begin
Result[i] := '0'
end else begin
Result[i] := '1';
end;
end;
end;
On the other hand, perhaps you are simply asking how to increment an address by one. Well, get the address and add one to it. There are two ways you might do this. If you want to deal with the address as a number, convert it to a pointer sized integer:
var
Address: UIntPtr;
....
Address := UIntPtr(@someVar);
And now you can perform arithmetic. For instance:
inc(Address);
Address := Address + 8;
and so on.
If you actually wish to perform pointer arithmetic and then de-reference the pointer, it's easier to use a pointer type. So, if you wish to pick out bytes, then you can do so like this:
var
BytePtr: PByte;
....
BytePtr := PByte(@someVar);
Now you can read a byte with
b := BytePtr^;
And the next one is:
inc(BytePtr);
b := BytePtr^;
Finally, if you wish to pull out the bytes that make up an integer, there is the LongRec
type for that. Write LongRec(someIntVar).Bytes[i]
to read one of the 4 bytes that make up an integer. Similar records WordRec
and Int64Rec
exist. These types are defined in SysUtils
.
这篇关于使用指针将十进制转换为二进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!