I'm new to Groovy. When I want convert some integer number to hex string, I have tried codes like this:
theNumber.toString(16)
as what I did in JavaScript. (Groovy is just like yet another script language looks similar to Java, right?)
But the code above not work as my expected. When the number is very large, the result is correct; but most of the time, it just return 16.
println(256.toString(16)) // 16
println(36893488147419103232.toString(16)) // 20000000000000000
I'm confused why Groovy behavior such strange. Could anyone help me to explain this? And, what is the best way to convert integer number to hex string?
Thanks.
Java is not JavaScript.
Groovy is a language built for the Java platform.
Java code also works directly with Groovy. So you can use .toHexString()
Integer.toHexString(256)
Long.toHexString(28562)
For numbers larger than the maximum value of long (9223372036854775807) the BigInteger datatype can be used.
String bigInt = new BigInteger("36893488147419103232").toString(16);
What you are calling is the static toString(int) from e.g. Integer. docs:
public static String toString(int i)
Returns a String object representing the specified integer. The argument is converted to signed decimal representation and returned as a string, exactly as if the argument and radix 10 were given as arguments to the toString(int, int) method.
E.g.:
groovy:000> Integer.toString(16)
===> 16
So what you want is:
groovy:000> Integer.toString(256,16)
===> 100
Related
I have a python string that looks like this:
byte_string = "01100110"
I want to turn this into a byte like so:
byte_byte = some_function(byte_string) # byte_byte = 0b01100110
How can I achieve this?
It appears you want to turn that string into a single number. For that you just convert to int with a base of 2.
byte_byte = int(byte_string, 2)
After reflecting on the question some more, I think I originally mis-understood your intent, which is reflected in my below "Prior Answer".
I'm thinking this prior SO question may address your question as well, as it sounds like you want to convert a string of 8 bits into a single byte.
And, as #Mark Ransom has indicated, it would look like this as a decimal code:
int(byte_string, 2)
output: 102
Or like this as the corresponding ascii character:
chr(int(byte_string, 2))
output: 'f'
----Prior Answer Based on Assumption of Encoding a String into an array of bytes------
You can encode a string to bytes like this, optionally passing the specific encoding if you want:
byte_string = "01100110"
byte_string.encode("utf-8")
bytes(byte_string, 'utf-8')
Result:
b'01100110'
Link to python docs for encoding / decoding strings.
Another option would be to create a bytearray:
bytearray(byte_string, 'utf-8')
output: bytearray(b'01100110')
And here is another StackOverflow thread that might be helpful as well, describing the difference between bytes and bytearray objects in relation to their use in converting to and from strings.
(I'm using Go 1.14.6.)
The following statements would all output the char a
Println(string(int(97) ) )
Println(string(int32(97) ) )
Println(string([]int32{97} ) )
But
Println(string([]int{97} ) )
would cause compile error
cannot convert []int literal (type []int) to type string
The behavior is confusing to me. If it handles string(int) the same as string(int32), why it handles string([]int) different from string([]int32)?
rune which represents a unicode code point is an alias for int32. So effectively string([]int32{}) is the same as string([]rune{}) which converts a slice of runes (something like the charaters of a string) to string. This is useful.
int is not int32 nor rune, so it's not logical what converting []int to string should be, it's ambiguous, so it's not allowed by the language spec.
Converting an integer number to string results in a string value with a single rune. Spec: Conversions:
Conversions to and from a string type
Converting a signed or unsigned integer value to a string type yields a string containing the UTF-8 representation of the integer. Values outside the range of valid Unicode code points are converted to "\uFFFD".
This is confusing to many, as many expects the conversion result to be the (decimal) representation as string. The Go authors have recognized this, and have taken steps to depcecate and remove it from the language in the future. In Go 1.15, go vet already warns for such conversion. Go 1.15 release notes: Vet:
New warning for string(x)
The vet tool now warns about conversions of the form string(x) where x has an integer type other than rune or byte. Experience with Go has shown that many conversions of this form erroneously assume that string(x) evaluates to the string representation of the integer x. It actually evaluates to a string containing the UTF-8 encoding of the value of x. For example, string(9786) does not evaluate to the string "9786"; it evaluates to the string "\xe2\x98\xba", or "☺".
Code that is using string(x) correctly can be rewritten to string(rune(x)). Or, in some cases, calling utf8.EncodeRune(buf, x) with a suitable byte slice buf may be the right solution. Other code should most likely use strconv.Itoa or fmt.Sprint.
This new vet check is enabled by default when using go test.
We are considering prohibiting the conversion in a future release of Go. That is, the language would change to only permit string(x) for integer x when the type of x is rune or byte. Such a language change would not be backward compatible. We are using this vet check as a first trial step toward changing the language.
I am learning Kotlin and I came across string template, and find it very amazing!
Soon I discovered that a number can be converted to string with the help of it.
I know that toString() is the recommended way. But I want to understand, is the below method advisable to use and what good is the efficiency?
fun main() {
val integer: Int = 19
val string1: String = "$integer"
val string2: String = integer.toString()
println(string1)
println(string2)
}
Output:
19
19
Check This SO thread to understand how string interpolation is actually implemented in kotlin:
Bottom line you'll have a StringBuilder that is created every time when you perform an interpolation. This alone makes this method less efficient then a "simple and straight-to-the-point" integer.toString()
An additional reason is code clarity I would say: the usage of string interpolation for conversion from integer to string looks non-intuitive - so use the right tool for the right job, you know :)
I'm pretty new to Python (never coded before in this language) and I need to pass a byte string to a function (as specified here[1]). It receives a string represents a binary number and I want to generate a byte string from it. I've tried countless things but I'm really stuck on how to do it, can you help me please?
I'm trying to pass this value to a library that handles DES, so I don't have any other option than doing it this way.
[1] https://www.dlitz.net/software/pycrypto/api/current/Crypto.Cipher.DES-module.html#new
from Crypto.Cipher import DES
key = "1101101110001000010000000000000100101000010000011000110100010100"
param = key.tobytes() # <-- The function I need
cipher = DES.new(key, DES.MODE_ECB)
Your key is in its current form a binary Number.
You could get the bytes (still as a string) from that simply with:
length = 8
input_l = [key[i:i+length] for i in range(0,len(key),length)]
And then convert each of these in a list to ints:
input_b = [int(b,base=2) for b in input_l]
The bytearray is then simply given by:
bytearray(input_b)
or
bytes(input_b)
depending on your usecase.
Converting this to a function is left as an exercise to the reader.
var trnlist = from tr in db.DebtorTransactions
join wr in db.Warranties
on tr.ProductID equals Convert.ToInt32(wr.PkfWarranty) into wrtd
from wr1 in db.Warranties
join sr in db.SalesReps
on wr1.fldSrId equals sr.pkfSrID into wrsr
from wr2 in db.Warranties
join ag in db.Agentsenter code here
on wr2.fldAgentID equals ag.pkfAgentID into wrag
select wrtd;
tr.ProductID is an int and wr.PKfWarranty is string.var rustul= convert.toint32(tr.ProductID) doesn't suitable for me.
Is there any built-in function of Linq to entity to do this?
Here you say:
tr.ProductID is a int
And then you try:
convert.toint32(tr.ProductID)
So... you're trying to convert an int to an int? In a comment you say:
the best overload method match for int.parse(string) has some invalid arguments
Well, if you're trying to call int.Parse() and passing it an int then you'd probably get that exact error. I imagine there's no overload for int.Parse() which accepts an int since, well, the value is already an int.
Let's look back at your problem description:
tr.ProductID is a int and wr.PKfWarranty is String
And you want to compare these two values? Then you'll either need to convert tr.ProductID to a string:
tr.ProductID.ToString()
or convert wr.PKfWarranty to an int:
int.Parse(wr.PKfWarranty)
A few things to note:
Converting from an int to a string is pretty safe, I doubt you'll ever have problems with that. However, converting from a string to an int assumes that the string can be converted to an int. This won't be the case if the string has anything in it that's not an int, or has a number too large to fit into the int data type. int.TryParse() exists for this purpose, but can be tricky to use in an in-line LINQ statement, especially when that statement is an expression tree which needs to produce SQL code.
If you convert the int to a string, there are different ways to compare strings. Depending on whether this is happening in resulting SQL code or in C# code makes a difference. If the latter, string.Equals() is the preferred method.