I am trying to convert small strings into their respective ascii decimal values. Like converting the string "Ag" to "065103".
I tried using
integer_variable : Integer := Integer'Value(Ag);
but that gives me constraint error: bad input for 'Value: "Ag".
Is there something else I can use to make this work? Could I just use enumeration?
Strings in Ada are arrays of Characters, thus if you want to convert String to Integer values you have to do this for each Character separately, by taking its position in enumeration (as suggested in the comment to your question). In your example it could be:
integer_variable1 : Natural := Character'Pos('A');
integer_variable2 : Natural := Character'Pos('g');
Related
This question already has answers here:
How to convert an int value to string in Go?
(10 answers)
Closed last year.
this is my day 1 using goLang, I am currently trying to consume a data but I encounter an error, and that's converting integer to string
func createLink(title string, page int) string {
url := url.URL{
Scheme: "https",
Host: "jsonmock.hackerrank.com",
Path: "/api/movies/search/",
}
query := url.Query()
query.Set("page", string(page))
query.Set("title", title)
url.RawQuery = query.Encode()
return url.String()
}
you can try that code, and the result is
actual result :
https://jsonmock.hackerrank.com/api/movies/search/?page=%01&title=spiderman
expected result :
https://jsonmock.hackerrank.com/api/movies/search/?page=1&title=spiderman
There's %01 , an that's something that I do not want. i believe that I made a mistake in converting an integer to string
You should use strconv.Itoa() method to format your integers as strings. This is better explained in the linked answer. For the sake of completeness, here's how you end up with %01 in your result:
first, int 1 gets "plain-converted" to string by following this conversion rule:
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".
then the resulting string (with character of unicode code point equal to 1) gets URL-encoded, ending up with %01 as its representation.
As a sidenote, you're warned about this if you run go vet over your code:
hello.go:19:20: conversion from int to string yields a string of one
rune, not a string of digits (did you mean fmt.Sprint(x)?)
While this doesn't always give you absolutely the best advice on how to fix your error, it at least pushed you into the right direction. And it's strongly recommended to get used to the idea of running this (or similar) kind of checks from day 1 of learning language.
I have specific questions for my project
input = "3d6"
I want to convert this string some parts to integer. For instance I want to use input[0] like integer.
How can I do this?
There's two problems here:
How to convert a string to an integer
The most straightforward method is the Atoi (ASCII to integer) function in the strconv package., which will take a string of numeric characters and coerce them into an integer for you.
How to extract meaningful components of a known string pattern
In order to use strconv.Atoi, we need the numeric characters of the input by themselves. There's lots of ways to slice and dice a string.
You can just grab the first and last characters directly - input[:1] and input[2:] are the ticket.
You could split the string into two strings on the character "d". Look at the split method, a member of the strings package.
For more complex problems in this space, regular expressions are used. They're a way to define a pattern the computer can look for. For example, the regular expression ^x(\d+)$ will match on any string that starts with the character x and is followed by one or more numeric characters. It will provide direct access to the numeric characters it found by themselves.
Go has first class support for regular expressions via its regexp package.
For example,
package main
import (
"fmt"
)
func main() {
input := "3d6"
i := int(input[0] - '0')
fmt.Println(i)
}
Playground: https://play.golang.org/p/061miKcXdIF
Output:
3
E.g.
input := "Office"
want := "4f6666696365" // Note: this is a string!!
I know that string literals are stored in UTF-8 already.
What is the easiest way to get convert this to string in UTF-8 representation?
Calling EncodeRune on each character seems too cumbersome.
What you're looking for is a string that contains the hex representation of your input string. That is not UTF-8. (Any string that's valid ASCII is also valid UTF-8.)
In any case, this is how to do what you want:
want := fmt.Sprintf("%x", []byte(input))
I have a data structure that I'd like to convert back and forth from hex to binary in Ruby. The simplest approach for a binary to hex is '0010'.to_i(2).to_s(16) - unfortunately this does not preserve leading zeroes (due to the to_i call), as one may need with data structures like cryptographic keys (which also vary with the number of leading zeroes).
Is there an easy built in way to do this?
I think you should have a firm idea of how many bits are in your cryptographic key. That should be stored in some constant or variable in your program, not inside individual strings representing the key:
KEY_BITS = 16
The most natural way to represent a key is as an integer, so if you receive a key in a hex format you can convert it like this (leading zeros in the string do not matter):
key = 'a0a0'.to_i(16)
If you receive a key in a (ASCII) binary format, you can convert it like this (leading zeros in the string do not matter):
key = '101011'.to_i(2)
If you need to output a key in hex with the right number of leading zeros:
key.to_s(16).rjust((KEY_BITS+3)/4, '0')
If you need to output a key in binary with the right number of leading zeros:
key.to_s(2).rjust(KEY_BITS, '0')
If you really do want to figure out how many bits might be in a key based on a (ASCII) binary or hex string, you can do:
key_bits = binary_str.length
key_bits = hex_str.length * 4
The truth is, leading zeros are not part of the integer value. I mean, it's a little detail related to representation of this value, not the value itself. So if you want to preserve properties of representation, it may be best not to get to underlying values at all.
Luckily, hex<->binary conversion has one neat property: each hexadecimal digit exactly corresponds to 4 binary digits. So assuming you only get binary numbers that have number of digits divisible by 4 you can just construct two dictionaries for constructing back and forth:
# Hexadecimal part is easy
hex = [*'0'..'9', *'A'..'F']
# Binary... not much longer, but a bit trickier
bin = (0..15).map { |i| '%04b' % i }
Note the use of String#% operator, that formats the given value interpreting the string as printf-style format string.
Okay, so these are lists of "digits", 16 each. Now for the dictionaries:
hex2bin = hex.zip(bin).to_h
bin2hex = bin.zip(hex).to_h
Converting hex to bin with these is straightforward:
"DEADBEEF".each_char.map { |d| hex2bin[d] }.join
Converting back is not that trivial. I assume we have a "good number" that can be split into groups of 4 binary digits each. I haven't found a cleaner way than using String#scan with a "match every 4 characters" regex:
"10111110".scan(/.{4}/).map { |d| bin2hex[d] }.join
The procedure is mostly similar.
Bonus task: implement the same conversion disregarding my assumption of having only "good binary numbers", i. e. "110101".
"I-should-have-read-the-docs" remark: there is Hash#invert that returns a hash with all key-value pairs inverted.
This is the most straightforward solution I found that preserves leading zeros. To convert from hexadecimal to binary:
['DEADBEEF'].pack('H*').unpack('B*').first # => "11011110101011011011111011101111"
And from binary to hexadecimal:
['11011110101011011011111011101111'].pack('B*').unpack1('H*') # => "deadbeef"
Here you can find more information:
Array#pack: https://ruby-doc.org/core-2.7.1/Array.html#method-i-pack
String#unpack1 (similar to unpack): https://ruby-doc.org/core-2.7.1/String.html#method-i-unpack1
I have "\001\022" as value of a. my desired decimal value is 274.
I tried following function . but I get ["0112"]
a.unpack("H*") ==> ["0112"]
When I convert this "0112" to decimal using calculator it gives me 274. How can i get like
this using ruby methods.
Thanks
The format string in your question: "H*", is for "hex string (high nibble first)". Therefore it decoded your string as an array of 4-bit hexadecimal elements.
You need a different format.
Try this, which decodes it as a "16-bit unsigned, network (big-endian) byte order" integer:
a.unpack("n") # => [274]
For full details on what characters you can use in the format string, check the Ruby Documentation for String#unpack.