I try to Encoding the std::string from UTF8,... to Hexadecimal. What I can't do right now is that I can't get the decimal value of each character of the input string to convert it if the input string contains special character which is from the Code Page Identifiers(windows-1258) include Vietnamese character.
At first, I will get the decimal value and then convert it to Binary and then to Hexadecimal. s is my input string. s = "Ồ".
void StringUtils::strToBinary(wstring s, string* result)
{
int n = s.length();
for (int i = 0; i < n; i++)
{
wchar_t c = s[i];
long val = long(c);
std::string bin = "";
while (val > 0)
{
(val % 2) ? bin.push_back('1') :
bin.push_back('0');
val /= 2;
}
reverse(bin.begin(), bin.end());
result->append(convertBinToHex(bin));
}
}
std::string StringUtils::convertBinToHex(std::string temp) {
long long binaryValue = atoll(temp.c_str());
long long dec_value = 0;
int base = 1;
int i = 0;
while (binaryValue) {
long long last_digit = binaryValue % 10;
binaryValue = binaryValue / 10;
dec_value += last_digit * base;
base = base * 2;
}
char hexaDeciNum[10];
while (dec_value != 0)
{
int temp = 0;
temp = dec_value % 16;
if (temp < 10)
{
hexaDeciNum[i] = temp + 48;
i++;
}
else
{
hexaDeciNum[i] = temp + 55;
i++;
}
dec_value = dec_value / 16;
}
std::string str;
for (int j = i - 1; j >= 0; j--) {
str = str + hexaDeciNum[j];
}
return str;
}
If my input only contain "Ồ" this is what my expected output
UTF8 : E1BB92
UTF16 : FEFF 1ED2
UTF16BE : 1ED2
UTF16LE : D21E
This how I do it in Java
Charset charset = Charset.forName(Enum.valueOf(Encoding.class, encodingType).toString());
ByteBuffer buffer = charset.newEncoder().encode(CharBuffer.wrap(inputString.toCharArray()));
byte[] bytes = new byte[buffer.limit()];
buffer.get(bytes, 0, buffer.limit());
result = new ByteField(bytes);
return result;
}
Related
Output
I am new in learning C programming. Now, I am trying to do SHA-1 for university project. I think this coding by myself. I am trying to do the message digest from the file above 55characters, which means 2 blocks is needed. The first block message digest is correct, but the second block is wrong. I have checked it very many times, but I still not able to find the mistake. Can anyone with experiences able to help me find it out? Thank you.
patients information.txt
"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int length,number_of_block,str_length;
unsigned int i = 0,j = 0,l = 0,e = 0,n = 0, t=0, k=0,f=0;
float x=0;
char c;
int H[5]={0x67452301,0xEFCDAB89,0x98BADCFE,0x10325476,0xC3D2E1F0};
unsigned int temp = 0;
FILE *file;
file = fopen("patients information.txt", "r");//Choose the file that want to access
if (file == NULL)//detect the file is empty or not
{
printf("The file is empty");
}
fseek(file, 0, SEEK_END);// move the file pointer to the end of the file
length = ftell(file);//calculate the length of sting in file
fseek(file, 0, SEEK_SET);// move file pointer back to start of file so we can read each character
printf("The length of string is %d\n",length);//check the number of character in string
char *string = malloc(sizeof(char) * (length+1));
while ( (c = fgetc(file)) != EOF)//pass the every character in the file to the string array
{
string[i] = c;
i++;
}
string[i] = '\0';//terminate the string storing
unsigned char long_msg[length+1];
for (i=0;i<length;i++)//pass the pointer array to the unsigned character array
{
long_msg[i]=string[i];
}
printf("The character store in th array is ");
long_msg[length]=128;
for (i=0;i<=length;i++)//check the message in msg array
{
printf("%X ",long_msg[i]);
}
if (length<=55)
{
number_of_block = 1;
}
else if (length>55 && length<120)
{
number_of_block = 2;
}
else
{
x = ((length - 55)/64);//calculate the number of block needed
number_of_block = x+2;
}
printf("\nNumber of block needed is %d\n",number_of_block);
unsigned char blocks[number_of_block][64];
for (i=0;i<number_of_block;i++)//Split the long string into n number of blocks
{
for(j=0;j<64;j++)
{
blocks[i][j]=long_msg[l];
if(l>length)//padding 0
{
blocks[i][j]=0;
}
l++;
}
}
for (i=0;i<number_of_block;i++)//check the blocks content
{
for(j=0;j<64;j++)
{
printf("%X ",blocks[i][j]);
}
}
printf("\nCheck length padding:\n");
str_length = 8*length;//sting length in bits
if (length<32)//if length of string is 1 bytes in hexadecimal
{
blocks[number_of_block-1][63]=str_length;
}
else
{
blocks[number_of_block-1][62]=(str_length>>8);//second last block
blocks[number_of_block-1][63]=((str_length<<8)>>8);//last block
}
for (i=0;i<number_of_block;i++)//check length padding
{
for(j=0;j<64;j++)
{
printf("%02X ",blocks[i][j]);
}
}
unsigned int w[number_of_block][16][4];
unsigned int W[number_of_block][80];
unsigned int A[number_of_block],B[number_of_block],C[number_of_block],D[number_of_block],E[number_of_block];
for (e=0;e<number_of_block;e++)
{
/*The problem is here*/
n=0;
for (i=0;i<16;i++)//split the padding message into w0 to w15 ,exp. w0 = (w[0][1]),....,(w[0][3])
{
for(j=0;j<4;j++)
{
w[e][i][j] = blocks[e][n];
n++;
}
}
for (i=0;i<16;i++)//combine the hex --> 16 block of hexadecimal(W0 to W15)
{
W[e][i] = ((w[e][i][0])<<24 | (w[e][i][1])<<16 | (w[e][i][2])<<8 | (w[e][i][3]));
}
/*Compute message digest*/
A[e] = 0x67452301;
B[e] = 0xEFCDAB89;
C[e] = 0x98BADCFE;
D[e] = 0x10325476;
E[e] = 0xC3D2E1F0;
for (t=0;t<=79;t++)
{
//for t = 16 -> 79
if (t>=16 && t<=79)//prepare W16 to W79
{
W[e][t]= ( (W[e][t-3]) ^ (W[e][t-8]) ^ (W[e][t-14]) ^ (W[e][t-16]) );
W[e][t]= ( ((W[e][t])<<1) | ((W[e][t]) >> (32-1)));//perform circular left shift
}
if (t>=0 && t<=19)
{
f = (B[e]&C[e]) | ((~B[e])&D[e]);
k = 0x5A827999;
}
else if (t>=20 && t<=39)
{
f = (B[e]^C[e]^D[e]);
k = 0x6ED9EBA1;
}
else if (t>=40 && t<=59)
{
f = (B[e]&C[e]) | (B[e]&D[e]) | (C[e]&D[e]);
k = 0x8F1BBCDC;
}
else if(t>=60 && t<=79)
{
f = (B[e]^C[e]^D[e]);
k = 0xCA62C1D6;
}
temp = ((A[e]<<5) | (A[e] >> (32-5))) + f + E[e] + W[e][t] + k;
E[e] = D[e];
D[e] = C[e];
C[e] = ( (B[e]<<30) | (B[e]>> (32-30)));
B[e] = A[e];
A[e] = temp;
}
printf("\n\n");
printf("%08X %08X %08X %08X %08X",A[e],B[e],C[e],D[e],E[e]);//check the value before adding up
H[0] = ( H[0] + A[e]);
H[1] = ( H[1] + B[e]);
H[2] = ( H[2] + C[e]);
H[3] = ( H[3] + D[e]);
H[4] = ( H[4] + E[e]);
}
printf("\n\n");
printf("Message digest:");
for (i=0;i<5;i++)
{
printf("%X ",H[i]);
}
printf("\n\n");
return 0;
}
The wrong output of second block : CE3A1FD0 01464A63 F6766B50 AF97AC62 8D5DBBDD
The output of second block should be: 906FD62C 58C0AAC0 B6A55520 74E9B89D 9AF00B7F
So i have small double values and i need to convert them into string in order to display in my app. But i care only about first two significant digits.
It should work like this:
convert(0.000000000003214324) = '0.0000000000032';
convert(0.000003415303) = '0.0000034';
We can convert double to string, then check every index and take up to two nonzero (also .) strings. But the issue comes on scientific notation for long double.
You can check Convert long double to string without scientific notation (Dart)
We need to find exact String value in this case. I'm taking help from this answer.
String convert(String number) {
String result = '';
int maxNonZeroDigit = 2;
for (int i = 0; maxNonZeroDigit > 0 && i < number.length; i++) {
result += (number[i]);
if (number[i] != '0' && number[i] != '.') {
maxNonZeroDigit -= 1;
}
}
return result;
}
String toExact(double value) {
var sign = "";
if (value < 0) {
value = -value;
sign = "-";
}
var string = value.toString();
var e = string.lastIndexOf('e');
if (e < 0) return "$sign$string";
assert(string.indexOf('.') == 1);
var offset =
int.parse(string.substring(e + (string.startsWith('-', e + 1) ? 1 : 2)));
var digits = string.substring(0, 1) + string.substring(2, e);
if (offset < 0) {
return "${sign}0.${"0" * ~offset}$digits";
}
if (offset > 0) {
if (offset >= digits.length) return sign + digits.padRight(offset + 1, "0");
return "$sign${digits.substring(0, offset + 1)}"
".${digits.substring(offset + 1)}";
}
return digits;
}
void main() {
final num1 = 0.000000000003214324;
final num2 = 0.000003415303;
final v1 = convert(toExact(num1));
final v2 = convert(toExact(num2));
print("num 1 $v1 num2 $v2");
}
Run on dartPad
This is a function if the endValueFixed is equal for example 12.0 I want to print the number without zero so I want it to be 12.
void calculateIncrease() {
setState(() {
primerResult = (startingValue * percentage) / 100;
endValue = startingValue + primerResult;
endValueFixe`enter code here`d = roundDouble(endValue, 2);
});
}
This may be an overkill but it works exactly as you wish:
void main() {
// This is your double value
final end = 98.04;
String intPart = "";
String doublePart = "";
int j = 0;
for (int i = 0; i < end.toString().length; i++) {
if (end.toString()[i] != '.') {
intPart += end.toString()[i];
} else {
j = i + 1;
break;
}
}
for (int l = j; l < end.toString().length; l++) {
doublePart += end.toString()[l];
}
if (doublePart[0] == "0" && doublePart[1] != "0") {
print(end);
} else {
print(end.toString());
}
}
You may use this code as a function and send whatever value to end.
if (endValueFixed==12) {
print('${endValueFixed.toInt()}');
}
conditionally cast it to an int and print it then :)
I wrote a program for a binary addition in java. But the result is sometimes not right.
For example if i add 1110+111. The result should be 10101.
But my program throws out 10001.
Maybe one of you find the mistake.
import java.util.Scanner;
public class BinaryAdder {
public static String add(String binary1, String binary2) {
int a = binary1.length()-1;
int b = binary2.length()-1;
int sum = 0;
int carry = 0;
StringBuffer sb = new StringBuffer();
while (a >= 0 || b >= 0) {
int help1 = 0;
int help2 = 0;
if( a >=0){
help1 = binary1.charAt(a) == '0' ? 0 : 1;
a--;
} if( b >=0){
help2 = binary2.charAt(b) == '0' ? 0 : 1;
b--;
}
sum = help1 +help2 +carry;
if(sum >=2){
sb.append("0");
carry = 1;
} else {
sb.append(String.valueOf(sum));
carry = 0;
}
}
if(carry == 1){
sb.append("1");
}
sb.reverse();
String s = sb.toString();
s = s.replaceFirst("^0*", "");
return s;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("First: ");
String input1 = scan.next("(0|1)*");
System.out.print("Second: ");
String input2 = scan.next("(0|1)*");
scan.close();
System.out.println("Result: " + add(input1, input2));
}
}
this function is much simpler :
public static String binaryAdd(String binary1,String binary2){
return Long.toBinaryString(Long.parseLong(binary1,2)+Long.parseLong(binary2,2));
}
you can change Long.parseLong into Integer.parseInt if you don't expect very large numbers, you can also replace parse(Long/Int) with parseUnsigned(Long/Int) since you don't expect your strings to have a minus sign do you ?
You are not considering the case when
help1 + help2 = 3
So your method String add(String binary1, String binary2) should be like this:
public static String add(String binary1, String binary2) {
int a = binary1.length()-1;
int b = binary2.length()-1;
int sum = 0;
int carry = 0;
StringBuffer sb = new StringBuffer();
while (a >= 0 || b >= 0) {
int help1 = 0;
int help2 = 0;
if( a >=0){
help1 = binary1.charAt(a) == '0' ? 0 : 1;
a--;
} if( b >=0){
help2 = binary2.charAt(b) == '0' ? 0 : 1;
b--;
}
sum = help1 +help2 +carry;
if (sum == 3){
sb.append("1");
carry = 1;
}
else if(sum ==2){
sb.append("0");
carry = 1;
} else {
sb.append(String.valueOf(sum));
carry = 0;
}
}
if(carry == 1){
sb.append("1");
}
sb.reverse();
String s = sb.toString();
s = s.replaceFirst("^0*", "");
return s;
}
I hope this could help you!
sum = help1 +help2 +carry;
if(sum >=2){
sb.append("0");
carry = 1;
} else {
sb.append(String.valueOf(sum));
carry = 0;
}
If sum is 2 then append "0" and carry = 1
What about when the sum is 3, append "1" and carry = 1
Will never be 4 or greater
Know I'm a bit late but I've just done a similar task so to anyone in my position, here's how I tackled it...
import java.util.Scanner;
public class Binary_Aids {
public static void main(String args[]) {
System.out.println("Enter the value you want to be converted");
Scanner inp = new Scanner(System.in);
int num = inp.nextInt();
String result = "";
while(num > 0) {
result = result + Math.floorMod(num, 2);
num = Math.round(num/2);
}
String flippedresult = "";
for(int i = 0; i < result.length(); i++) {
flippedresult = result.charAt(i) + flippedresult;
}
System.out.println(flippedresult);
}
}
This took an input and converted to binary. Once here, I used this program to add the numbers then convert back...
import java.util.Scanner;
public class Binary_Aids {
public static void main(String args[]) {
Scanner inp = new Scanner(System.in);
String decimalToBinaryString = new String();
System.out.println("First decimal number to be added");
int num1 = inp.nextInt();
String binary1 = decimalToBinaryString(num1);
System.out.println("Input decimal number 2");
int num2 = inp.nextInt();
String binary2 = decimalToBinaryString(num2);
int patternlength = Math.max[binary1.length[], binary2.length[]];
while(binary1.length() < patternlength) {
binary1 = "0" + binary2;
}
System.out.println(binary1);
System.out.println(binary2);
int carry = 0;
int frequency_of_one;
String result = "";
for(int i = patternlength -i; i >= 0; i--) {
frequency_of_one = carry;
if(binary1.charAt(i) == '1') {
frequency_of_one++;
}
if(binary2.charAt(i) == '1') {
frequency_of_one++;
}
switch(frequency_of_one) {
case 0 ;
carry = 0;
result = "1" + result;
break;
case 1 ;
carry = 0;
result = "1" + result;
break;
case 2;
carry = 1;
result = "0" + result;
breake;
case 3;
carry = 1;
result = "1" + result;
breake;
}
}
if(carry == 1) {
result = "1" + result;
}
System.out.println(result);
}
public static String decimalToBinaryString(int decimal1) {
String result = "";
while(decimal1 > 0) {
result = result + Math.floorMod(decimal1, 2);
decimal = Math.round(decimal1/2);
}
String flipresult = "";
for(int i = 0; i < result.length[]; i++) {
flipresult = result.charAt(i) + flippedresult;
}
return flippedresult;
}
}
X++ method to calculate Easter Sunday?
static date dateOfEaster(Yr y)
{
int a = y mod 19;
int b = y div 100;
int c = y mod 100;
int d = b div 4;
int e = b mod 4;
int f = (b+8) div 25;
int g = (b-f+1) div 3;
int h = (19*a+b-d-g+15) mod 30;
int i = c div 4;
int k = c mod 4;
int l = (32+2*e+2*i-h-k) mod 7;
int m = (a+11*h+22*l) div 451;
int n = (h+l-7*m+114) div 31;
int p = (h+l-7*m+114) mod 31;
return mkdate(p+1,n,y);
}
I got a little creative so you can enumerate all of the holidays for a given year using GET with a public web service and a little recursion. Play around with this as you like. Just copy/paste to a JOB:
static void HolidayWebService(Args _args)
{
System.Net.WebClient webClient = new System.Net.WebClient();
str holidaysAvailable = "http://www.holidaywebservice.com/HolidayService_v2/HolidayService2.asmx/GetHolidaysAvailable?countryCode=UnitedStates";
str holidayDate = "http://www.holidaywebservice.com/HolidayService_v2/HolidayService2.asmx/GetHolidayDate?countryCode=%1&holidayCode=%2&year=%3";
str retVal = webClient.DownloadString(holidaysAvailable);
XMLDocument doc=XMLDocument::newXml(retVal);
XmlNamedNodemap attributes;
XmlElement root = doc.root();
XmlNode node = root.firstChild();
void getHolidayDate(str _holidayCode, Yr _yr = datetimeutil::year(datetimeutil::utcNow()), str _countryCode = 'UnitedStates')
{
System.Net.WebClient webClientInner = new System.Net.WebClient();
str locRetVal;
;
try
{
locRetVal = webClientInner.DownloadString(strfmt(holidayDate, _countryCode, _holidayCode, _yr));
info(strfmt("[%1] %2", _holidayCode, locRetVal));
}
catch
{
error(strfmt("Error with %1, %2, %3", _holidayCode, _yr, _countryCode));
continue;
}
}
void dig(XmlNode _node, int _depth = 0)
{
XmlNode sib;
;
if (_node == null)
return;
if (_node.hasChildNodes())
dig(_node.firstChild(), (_depth+1));
else
{
if (_node.parentNode().name() == 'CODE')
getHolidayDate(_node.innerText());
}
sib = _node.nextSibling();
if (sib)
dig(sib);
}
;
dig(node);
}