I'm trying to create a QString which is a hexadecimal number with its letter digits in Capitals instead of small caps, how can it be done?
QString( " %1" ).arg( 15, 1, 16 )
yields f and I'd like F
By converting the string to upper case:
QString( " %1" ).arg( 15, 1, 16 ).toUpper();
This returns an uppercase string. The method used to be called upper() in qt3.
Related
I need to be able to count the instances of a period in a string. (I need to capture the decimal point in a number, but discard the other periods in the name or title.) I know NUM-ENTRIES essentially counts the number of entries around that character, but I want to do the opposite. My broader problem is to parse a decimal number out of a string, where occasionally the string has other periods in the string.
What syntax can I use to determine the number of periods in this string? See my pretend "NUM-PERIODDS" pretend Progess function below.
Erin L. Halpin (33.333%)
Mr. Thomas Q. Smith 66.6%
I have an algorith to take everything in front of the "%" sign, then I process through all the numbers, but if I find a second "." then I need to skip that character. (If there are better ways to do my algorithm, would love suggestions on that, too.)
//takes in the full joint name and sees if there is a percentage value in it
//then finds whatever is in front of the % sign
IF INDEX (full_name_percentage, "%") GT 0 THEN DO:
cBeforePercentageStr=
SUBSTRING(full_name_percentage,1,INDEX(full_name_percentage,"%") - 1).
IF LENGTH (cBeforePercentageStr) GT 0 THEN DO:
//MESSAGE full_name_percentage VIEW-AS ALERT-BOX.
cThisChar = "".
DO iTemp = 1 TO LENGTH(cBeforePercentageStr):
cThisChar = SUBSTRING(cBeforePercentageStr,iTemp,1).
IF fnIsNumericOrPeriod(cThisChar) THEN
cPercentage = cPercentage + cThisChar.
END.
//need to account for if there are two decimal points
IF **NUM-PERIODS** (cPercentage, ".") GT 1 THEN DO:
MESSAGE "cPercentage value " + cPercentage VIEW-AS ALERT-BOX.
cPercentage = SUBSTRING(cPercentage,2,LENGTH(cPercentage)).
END.
dPercent = TRUNCAT (DECIMAL(cPercentage),2).
END.
END.
There is no need for loops. The number of characters in a string is equal to the length of the string minus the length of that same string without those characters.
define variable p as integer no-undo.
define variable myString as character no-undo.
myString = 'Erin L. Halpin (33.333%) Mr. Thomas Q. Smith 66.6%'.
p = length( myString )
- length( replace( myString, '.', '' ) )
.
message 'there are' p 'periods in the string'.
Golfing on you can also just return the number of entries with "." as delimiter minus one but with a floor of 0.
DEFINE VARIABLE i AS INTEGER NO-UNDO.
DEFINE VARIABLE cStr AS CHARACTER NO-UNDO.
cStr = 'Erin L. Halpin (33.333%) Mr. Thomas Q. Smith 66.6%'.
i = MAX(NUM-ENTRIES(cStr, ".") - 1,0) .
MESSAGE SUBSTITUTE("There are &1 periods in the string", i) VIEW-AS ALERT-BOX.
I like Stefan's idea (and it's pretty foolproof) but for a bit of code golf fun, you can loop without looping all the characters ...
DEFINE VARIABLE str AS CHARACTER NO-UNDO.
DEFINE VARIABLE findChr AS CHARACTER NO-UNDO.
DEFINE VARIABLE cnt AS INTEGER NO-UNDO.
DEFINE VARIABLE pos AS INTEGER NO-UNDO.
DEFINE VARIABLE startPos AS INTEGER NO-UNDO.
str = "Erin L. Halpin (33.333%) Mr. Thomas Q. Smith 66.6%".
findChr = ".".
startPos = 1.
pos = INDEX(str, findChr, startPos).
DO while pos > 0:
cnt = cnt + 1.
startpos = pos + 1.
pos = INDEX(str, findChr, startPos).
eND.
MESSAGE
cnt
VIEW-AS ALERT-BOX.
This is kind of crude and ugly but it should work just fine:
define variable i as integer no-undo.
define variable n as integer no-undo.
define variable p as integer no-undo.
define variable myString as character no-undo.
myString = "Erin L. Halpin (33.333%) Mr. Thomas Q. Smith 66.6%".
n = length( myString ).
do i = 1 to n:
if substring( myString, i, 1 ) = "." then p = p + 1.
end.
message "there are" p "periods in the string".
I'm new to LUA but figured out that gsub is a global substitution function and tonumber is a converter function. What I don't understand is how the two functions are used together to produce an encoded string.
I've already tried reading parts of PIL (Programming in Lua) and the reference manual but still, am a bit confused.
local L0_0, L1_1
function L0_0(A0_2)
return (A0_2:gsub("..", function(A0_3)
return string.char((tonumber(A0_3, 16) + 256 - 13 + 255999744) % 256)
end))
end
encodes = L0_0
L0_0 = gg
L0_0 = L0_0.toast
L1_1 = "__loading__\226\128\166"
L0_0(L1_1)
L0_0 = encodes
L1_1 = --"The Encoded String"
L0_0 = L0_0(L1_1)
L1_1 = load
L1_1 = L1_1(L0_0)
pcall(L1_1)
I removed the encoded string where I put the comment because of how long it was. If needed I can upload the encoded string as well.
gsub is being used to get 2 digit sections of A0_2. This means the string A0_3 is a 2 digit hexadecimal number but it is not in a number format so we cannot preform math on the value. A0_3 being a hex number can be inferred based on how tonubmer is used.
tonumber from Lua 5.1 Reference Manual:
Tries to convert its argument to a number. If the argument is already a number or a string convertible to a number, then tonumber returns this number; otherwise, it returns nil.
An optional argument specifies the base to interpret the numeral. The base may be any integer between 2 and 36, inclusive. In bases above 10, the letter 'A' (in either upper or lower case) represents 10, 'B' represents 11, and so forth, with 'Z' representing 35. In base 10 (the default), the number can have a decimal part, as well as an optional exponent part (see ยง2.1). In other bases, only unsigned integers are accepted.
So tonumber(A0_3, 16) means we are expecting for A0_3 to be a base 16 number (hexadecimal).
Once we have the number value of A0_3 we do some math and finally convert it to a character.
function L0_0(A0_2)
return (A0_2:gsub("..", function(A0_3)
return string.char((tonumber(A0_3, 16) + 256 - 13 + 255999744) % 256)
end))
end
This block of code takes a string of hex digits and converts them into chars. tonumber is being used to allow for the manipulation of the values.
Here is an example of how this works with Hello World:
local str = "Hello World"
local hex_str = ''
for i = 1, #str do
hex_string = hex_string .. string.format("%x", str:byte(i,i))
end
function L0_0(A0_2)
return (A0_2:gsub("..", function(A0_3)
return string.char((tonumber(A0_3, 16) + 256 - 13 + 255999744) % 256)
end))
end
local encoded = L0_0(hex_str)
print(encoded)
Output
;X__bJbe_W
And taking it back to the orginal string:
function decode(A0_2)
return (A0_2:gsub("..", function(A0_3)
return string.char((tonumber(A0_3, 16) + 13) % 256)
end))
end
hex_string = ''
for i = 1, #encoded do
hex_string = hex_string .. string.format("%x", encoded:byte(i,i))
end
print(decode(hex_string))
I look some solution in this site but those not works in python 3.7.
So, I asked a new question.
Hex string of "the" is "746865"
I want to a solution to convert "the" to "746865" and "746865" to "the"
Given that your string contains ascii only (each char is in range 0-0xff), you can use the following snippet:
In [28]: s = '746865'
In [29]: import math
In [30]: int(s, base=16).to_bytes(math.ceil(len(s) / 2), byteorder='big').decode('ascii')
Out[30]: 'the'
Firstly you need to convert a string into integer with base of 16, then convert it to bytes (assuming 2 chars per byte) and then convert bytes back to string using decode
#!/usr/bin/python3
"""
Program name: txt_to_ASC.py
The program transfers
a string of letters -> the corresponding
string of hexadecimal ASCII-codes,
eg. the -> 746865
Only letters in [abc...xyzABC...XYZ] should be input.
"""
print("Transfer letters to hex ASCII-codes")
print("Input range is [abc...xyzABC...XYZ].")
print()
string = input("Input set of letters, eg. the: ")
print("hex ASCII-code: " + " "*15, end = "")
def str_to_hasc(x):
global glo
byt = bytes(x, 'utf-8')
bythex = byt.hex()
for b1 in bythex:
y = print(b1, end = "")
glo = str(y)
return glo
str_to_hasc(string)
If you have a byte string, then:
>>> import binascii
>>> binascii.hexlify(b'the')
b'746865'
If you have a Unicode string, you can encode it:
>>> s = 'the'
>>> binascii.hexlify(s)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: a bytes-like object is required, not 'str'
>>> binascii.hexlify(s.encode())
b'746865'
The result is a byte string, you can decode it to get a Unicode string:
>>> binascii.hexlify(s.encode()).decode()
'746865'
The reverse, of course, is:
>>> binascii.unhexlify(b'746865')
b'the'
#!/usr/bin/python3
"""
Program name: ASC_to_txt.py
The program's input is a string of hexadecimal digits.
The string is a bytes object, and each byte is supposed to be
the hex ASCII-code of a (capital or small) letter.
The program's output is the string of the corresponding letters.
Example
Input: 746865
First subresult: ['7','4','6','8','6','5']
Second subresult: ['0x74', '0x68', '0x65']
Third subresult: [116, 104, 101]
Final result: the
References
Contribution by alhelal to stackoverflow.com (20180901)
Contribution by QintenG to stackoverflow.com (20170104)
Mark Pilgrim, Dive into Python 3, section 4.6
"""
import string
print("The program converts a string of hex ASCII-codes")
print("into the corresponding string of letters.")
print("Input range is [41, 42, ..., 5a] U [61, 62, ..., 7a]. \n")
x = input("Input the hex ASCII-codes, eg. 746865: ")
result_1 = []
for i in range(0,len(x)//2):
for j in range(0,2):
result_1.extend(x[2*i+j])
# First subresult
lenres_1 = len(result_1)
result_2 = []
for i in range(0,len(result_1) - 1,2):
temp = ""
temp = temp + "0x" + result_1[i] #0, 2, 4
temp = temp + result_1[i + 1] #1, 3, 5
result_2.append(temp)
# Second subresult
result_3 = []
for i in range(0,len(result_2)):
result_3.append(int(result_2[i],16))
# Third subresult
by = bytes(result_3)
result_4 = by.decode('utf-8')
# Final result
print("Corresponding string of letters:" + " "*6, result_4, end = "\n")
I know we can declare an integer in base 2, 8, 10, or 16, for example:
0b10000
0o20
16
0x10
all result in the integer 16.
But given an integer, for example 43981, how do I get its hexadecimal representation?
Use Integer.to_string/2 with 16 as the second argument.
Integer.to_string(43981, 16) # "ABCD"
You can also get the binary and octal representations the same way:
Integer.to_string(43981, 2) # "1010101111001101"
Integer.to_string(43981, 8) # "125715"
I want to retrieve like in Pic2, the values in Decimal. ( hardcoded for visual understanding)
This is the codes to convert Hex to Dec for 16 bit:
string H;
int D;
H = txtHex.Text;
D = Convert.ToInt16(H, 16);
txtDec.Text = Convert.ToString(D);
however it doesn't work for a whole group
So the hex you are looking at does not refer to a decimal number. If it did refer to a single number that number would be far too large to store in any integral type. It might actually be too large to store in floating point types.
That hex you are looking at represents the binary data of a file. Each set of two characters represents one byte (because 16^2 = 2^8).
Take each pair of hex characters and convert it to a value between 0 and 255. You can accomplish this easily by converting each character to its numerical value. In case you don't have a complete understanding of what hex is, here's a map.
'0' = 0
'1' = 1
'2' = 2
'3' = 3
'4' = 4
'5' = 5
'6' = 6
'7' = 7
'8' = 8
'9' = 9
'A' = 10
'B' = 11
'C' = 12
'D' = 13
'E' = 14
'F' = 15
If the character on the left evaluates to n and the character on the right evaluates to m then the decimal value of the hex pair is (n x 16) + m.
You can use this method to get your values between 0 and 255. You then need to store each value in an unsigned char (this is a C/C++/ObjC term - I have no idea what the C# or VBA equivalent is, sorry). You then concatenate these unsigned char's to create the binary of the file. It is very important that you use an 8 bit type to store these values. You should not store these values in 16 bit integers, as you do above, or you will get corrupted data.
I don't know what you're meant to output in your program but this is how you get the data. If you provide a little more information I can probably help you use this binary.
You will need to split the contents into separate hex-number pairs ("B9", "D1" and so on). Then you can convert each into their "byte" value and add it to a result list.
Something like this, although you may need to adjust the "Split" (now it uses single spaces, returns, newlines and tabs as separator):
var byteList = new List<byte>();
foreach(var bytestring in txtHex.Text.Split(new[] {' ', '\r', '\n', '\t'},
StringSplitOptions.RemoveEmptyEntries))
{
byteList.Add(Convert.ToByte(bytestring, 16));
}
byte[] bytes = byteList.ToArray(); // further processing usually needs a byte-array instead of a List<byte>
What you then do with those "bytes" is up to you.