String Julia中整数到字符串的转换

String Julia中整数到字符串的转换,string,floating-point,type-conversion,julia,String,Floating Point,Type Conversion,Julia,我想在Julia中将整数转换为字符串 当我尝试时: a = 9500 b = convert(String,a) 我得到一个错误: ERROR: LoadError: MethodError: Cannot `convert` an object of type Int64 to an object of type String This may have arisen from a call to the constructor String(...), since type constru

我想在Julia中将整数转换为字符串

当我尝试时:

a = 9500
b = convert(String,a)
我得到一个错误:

ERROR: LoadError: MethodError: Cannot `convert` an object of type Int64 to an object of type String
This may have arisen from a call to the constructor String(...),
since type constructors fall back to convert methods.
 in include_from_node1(::String) at ./loading.jl:488
 in process_options(::Base.JLOptions) at ./client.jl:265
 in _start() at ./client.jl:321
while loading ..., in expression starting on line 16
我不知道为什么Int64不能转换成字符串

我曾尝试将
a
定义为不同的类型,例如
a=UInt64(9500)
,但得到了类似的错误

我知道这是一个非常基本的方法,我已经尝试过寻找正确的方法来实现这一点,但没有找到正确的方法。

您应该使用:

b = string(a)

string
函数可用于使用
print
repr
使用
showall
从任何值创建字符串。在
Int64
的情况下,这是等效的

事实上,这可能就是转换不起作用的原因——因为根据基的选择,有很多方法可以将整数转换为字符串

编辑

对于整数,您也可以使用
bin
dec
hex
oct
base
将它们转换为字符串

在Julia 1.0之前,您可以使用带有整数的
base
关键字参数的函数在不同的基中进行转换。还有一个
bitstring
函数,它给出数字的文字位表示。以下是一些例子:

julia> string(100)
"100"

julia> string(100, base=16)
"64"

julia> string(100, base=2)
"1100100"

julia> bitstring(100)
"0000000000000000000000000000000000000000000000000000000001100100"

julia> bitstring(UInt8(100))
"01100100"

julia> string(100.0)
"100.0"

julia> string(100.0, base=2)
ERROR: MethodError: no method matching string(::Float64; base=2)
Closest candidates are:
  string(::Any...) at strings/io.jl:156 got unsupported keyword argument "base"
  string(::String) at strings/substring.jl:146 got unsupported keyword argument "base"
  string(::SubString{String}) at strings/substring.jl:147 got unsupported keyword argument "base"
  ...
Stacktrace:
 [1] top-level scope at none:0

julia> bitstring(100.0)
"0100000001011001000000000000000000000000000000000000000000000000"

?副本。投票结束。小更正:
string
可用于将任何值转换为
AbstractString
的子类型,即
string
的输出不总是
string
bin
hex
base
等类型。不推荐使用。新的打印方式是:
string(42,base=2)
。它还支持填充。
julia> string(100)
"100"

julia> string(100, base=16)
"64"

julia> string(100, base=2)
"1100100"

julia> bitstring(100)
"0000000000000000000000000000000000000000000000000000000001100100"

julia> bitstring(UInt8(100))
"01100100"

julia> string(100.0)
"100.0"

julia> string(100.0, base=2)
ERROR: MethodError: no method matching string(::Float64; base=2)
Closest candidates are:
  string(::Any...) at strings/io.jl:156 got unsupported keyword argument "base"
  string(::String) at strings/substring.jl:146 got unsupported keyword argument "base"
  string(::SubString{String}) at strings/substring.jl:147 got unsupported keyword argument "base"
  ...
Stacktrace:
 [1] top-level scope at none:0

julia> bitstring(100.0)
"0100000001011001000000000000000000000000000000000000000000000000"